编写一个程序Java,该程序创建三个新线程(已经存在的主线程除外) 并使它们同步,以使每个线程依次显示其线程ID进行5次迭代。 程序的输出应如下所示:
线程1-迭代编号。 1
线程2-迭代编号1
线程3-迭代编号1
线程1-迭代编号。 2
线程2-迭代编号2
线程3-迭代编号2
线程1-迭代编号。 3
线程2-迭代编号3
线程3-迭代编号3
线程1-迭代编号。 4
线程2-迭代编号4
线程3-迭代编号4
线程1-迭代编号。 5
线程2-迭代编号5
线程3-迭代编号5
代码:
package ZTest;
public class PrintSequenceRunnable2 implements Runnable{
public int PRINT_NUMberS_UPTO=15;
static int number=1;
int remainder;
static Object lock=new Object();
PrintSequenceRunnable2(int remainder)
{
this.remainder=remainder;
}
public void run() {
while (number < PRINT_NUMberS_UPTO-1) {
synchronized (lock) {
while (number % 3 != remainder) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "- iteration no. " + number);
number++;
lock.notifyAll();
}
}
}
public static void main(String[] args) {
PrintSequenceRunnable2 runnable1=new PrintSequenceRunnable2(1);
PrintSequenceRunnable2 runnable2=new PrintSequenceRunnable2(2);
PrintSequenceRunnable2 runnable3=new PrintSequenceRunnable2(0);
Thread t1=new Thread(runnable1,"Thread1");
Thread t2=new Thread(runnable2,"Thread2");
Thread t3=new Thread(runnable3,"Thread3");
t1.start();
t2.start();
t3.start();
}
}
我的输出:
Thread1- iteration no. 1
Thread2- iteration no. 2
Thread3- iteration no. 3
Thread1- iteration no. 4
Thread2- iteration no. 5
Thread3- iteration no. 6
Thread1- iteration no. 7
Thread2- iteration no. 8
Thread3- iteration no. 9
Thread1- iteration no. 10
Thread2- iteration no. 11
Thread3- iteration no. 12
Thread1- iteration no. 13
Thread2- iteration no. 14
Thread3- iteration no. 15
预期输出:
Thread 1 - iteration no. 1
Thread 2 - iteration no. 1
Thread 3 - iteration no. 1
Thread 1 - iteration no. 2
Thread 2 - iteration no. 2
Thread 3 - iteration no. 2
Thread 1 - iteration no. 3
Thread 2 - iteration no. 3
Thread 3 - iteration no. 3
Thread 1 - iteration no. 4
Thread 2 - iteration no. 4
Thread 3 - iteration no. 4
Thread 1 - iteration no. 5
Thread 2 - iteration no. 5
Thread 3 - iteration no. 5