Java:写2个线程,其中一个线程打印1-52,另一个线程打印A-Z,打印顺序应该是12A34B56C...5152Z。
生活随笔
收集整理的這篇文章主要介紹了
Java:写2个线程,其中一个线程打印1-52,另一个线程打印A-Z,打印顺序应该是12A34B56C...5152Z。
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
寫2個(gè)線程,其中一個(gè)線程打印1-52,另一個(gè)線程打印A-Z,打印順序應(yīng)該是12A34B56C...5152Z
?
多線程編程:使用Runnable接口實(shí)例創(chuàng)建線程。使用線程等待方法wait();
package com.java瘋狂講義;public class Print {//flag==true時(shí),打印數(shù)字;private boolean flag = true;//要打印數(shù)字的起始數(shù)private int num = 0;public synchronized void printNumber() throws InterruptedException {if (!flag) {this.wait();}for (int i = 0; i < 2; i++) {System.out.println(++num + "\t");}flag = false;this.notify();}public synchronized void printChar(int i) throws InterruptedException {if (flag) {this.wait();}System.out.println((char)('A' + i )+ "\t");flag = true;this.notify();} }
測(cè)試類:
package com.java瘋狂講義;public class Test {public static void main(String[] args){Print print = new Print();new Thread(new Runnable() {@Overridepublic void run() {for(int i =0;i<26;i++){try{print.printNumber();}catch(InterruptedException e){e.printStackTrace();}}}}).start();new Thread(new Runnable() {@Overridepublic void run() {for(int i =0;i<26;i++){try{print.printChar(i);}catch(InterruptedException e){e.printStackTrace();}}}}).start();}}?
總結(jié)
以上是生活随笔為你收集整理的Java:写2个线程,其中一个线程打印1-52,另一个线程打印A-Z,打印顺序应该是12A34B56C...5152Z。的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JAVA多线程:线程创建过程以及生命周期
- 下一篇: Java:假设车库有3个车位(可以通过b