用生产者和消费者模型实现交替输出奇数和偶数
要求:t1–>1,t2–>2,t1–>3…
废话不多说直接上代码
package thread;
public class MyThread7 {
public static void main(String[] args) {
Num num=new Num(1);
Thread t1=new Thread(new MyRun1(num));
t1.setName("t1");
Thread t2=new Thread(new MyRun2(num));
t2.setName("t2");
t2.start();
t1.start();
}
}
class Num{
int i;
public Num(){
}
public Num(int i){
this.i=i;
}
}
class MyRun1 implements Runnable{
private Num num;
public MyRun1(Num num){
this.num=num;
}
@Override
public void run() {
while(true){
synchronized (num){
if((num.i)%2==0){
try {
num.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"--->"+num.i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num.notifyAll();
}
}
}
}
class MyRun2 implements Runnable{
private Num num;
public MyRun2(Num num){
this.num=num;
}
@Override
public void run() {
while(true){
synchronized (num){
if((num.i)%2==1){
try {
num.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"--->"+num.i++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num.notifyAll();
}
}
}
}