【发布时间】:2014-08-01 14:40:08
【问题描述】:
我想开发一个包含两个线程thread1 和thread2 的应用程序。 线程 1 必须打印最多 50 的偶数,线程 2 必须打印最多 50 的奇数。 并且两个线程都应该进行通信,以便打印顺序应该是 1,2,50。 我尝试了以下代码。 EvenThread和OddThread如何通信
public class TestPrint{
public static void main(String[] args) {
EvenThread et=new EvenThread();
OddThread ot=new OddThread();
et.start();
ot.start();
}
}
class EvenThread extends Thread{
int even=0;
@Override
public void run() {
synchronized(this){
while(even<50){
System.out.println(even);
even=even+2;
try {
this.wait();
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class OddThread extends Thread{
int odd=1;
@Override
public void run() {
synchronized(this){
while(odd<50){
System.out.println(odd);
odd=odd+2;
try {
this.wait();
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
【问题讨论】:
-
如果需要按顺序执行,为什么还要同时执行它们?
标签: java multithreading synchronization wait notify