问题要求:
1.使用5个线程
2.五个线程依次打印1A2B…,即第一个线程负责打印1(A、F)等等。
解决思路:
1.轮询count ,当count满足当前线程的打印条件后,打印
2.采用wait和notifyAll进行通信
相关方法:
1.wait()方法的作用是将当前运行的线程挂起(即让其进入阻塞状态),直到notify或notifyAll方法来唤醒线程.
2.notify和notifyAll的区别在于前者只能唤醒monitor上的一个线程,对其他线程没有影响,而notifyAll则唤醒所有的线程
实验代码:
public class PrintLettersInorder {
static Object object = new Object();
static int count = 0 ;
static class MyPrintThread extends Thread{
int index ;
public MyPrintThread(int index){
this.index = index;
}
@Override
public void run() {
synchronized (object){
while (count < 26){
try{
//满足打印条件后,打印并将count+1,然后唤醒其他线程,不满足条件则挂起
if (count%5 == (index-1)){
char c = (char) ('A' + count) ;
System.out.println(index+""+c);
count++ ;
object.notifyAll();//唤醒其他线程
}
//不满足条件,挂起
object.wait();
}catch (InterruptedException ex){
ex.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread thread1 = new MyPrintThread(1);
Thread thread2 = new MyPrintThread(2);
Thread thread3 = new MyPrintThread(3);
Thread thread4 = new MyPrintThread(4);
Thread thread5 = new MyPrintThread(5);
thread1.start();
thread2.start();
thread3.start();
thread4.start();
thread5.start();
while (count < 26);
System.exit(0);
}
}
实验结果:
1A
2B
3C
4D
5E
1F
2G
3H
4I
5J
1K
2L
3M
4N
5O
1P
2Q
3R
4S
5T
1U
2V
3W
4X
5Y
1Z
存在一个问题,线程没有结束,于是在主线程里面加了 如下代码:
while (count < 26);
System.exit(0);
使得26个字母打印完后程序结束