启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5, 然后是线程2打印6,7,8,9,10, 然后是线程3打印11,12,13,14,15. 接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75. 程序的输出结果应该为:
线程1: 1
线程1: 2
线程1: 3
线程1: 4
线程1: 5
线程2: 6
线程2: 7
线程2: 8
线程2: 9
线程2: 10
...
线程3: 71
线程3: 72
线程3: 73
线程3: 74
线程3: 75
public class PrintNoDemo {
private static int printNO = 1;
private static int printThread = 1;
private static Condition condition1;
private static Condition condition2;
private static Condition condition3;
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args){
condition1 = lock.newCondition();
condition2 = lock.newCondition();
condition3 = lock.newCondition();
for(int i=0; i<3; i++){
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
while(printNO <= 75){
printNo();
}
}
},"线程"+(i+1));
thread.start();
}
}
public static void printNo() {
try {
lock.lock();
String threadName = Thread.currentThread().getName();
//判断线程,选择等待Condition
if(!threadName.equals("线程"+printThread)){
if(threadName.equals("线程1")){
condition1.await();
} else
if(threadName.equals("线程2")){
condition2.await();
} else
if(threadName.equals("线程3")){
condition3.await();
}
}
//处理打印
for (int i = 0; i
if(printNO > 75){
break;
}
System.out.println(Thread.currentThread().getName() +":"+ printNO++);
}
//获取下一个打印线程
printThread = printThread%3 +1;
if(threadName.equals("线程1")){
condition2.signal();
}else
if(threadName.equals("线程2")){
condition3.signal();
}else
if(threadName.equals("线程3")){
condition1.signal();
}
// lock.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
网友实现方法
class NumberPrinter extends Thread {
static int c = 0;
static int state = 0;
private int id;
@Override
public synchronized void run() {
while (state
if (state % 3 == id) {
for (int j = 0; j
c++;
System.out.format("Thread %d: %d %n", id, c);
}
state++;;
}
}
}
public NumberPrinter(int id) {
this.id = id;
}
public static void main(String[] args) {
for (int i = 0; i
new NumberPrinter(i).start();
}
}
}