使用生产者和消费者模式,交替输出奇数偶数
t1-1
t2-2
t1-3
t2-4
…
要求两个线程共享一个数字,交替输出
public class ThreadTest {
public static void main(String[] args) {
Num num=new Num();
Thread t1=new Thread(new MyThreadOne(num));
Thread t2=new Thread(new MyThreadTwo(num));
t1.setName("奇数");
t2.setName("偶数");
t1.start();
t2.start();
}
}
//创建数字类
class Num{
int i=1;//设定初始值为1
}
//输出奇数的线程
class MyThreadOne implements Runnable{
private Num num;
public MyThreadOne(Num number) {
this.num = number;
}
@Override
public void run() {
//一直输出奇数
while (true){
//上锁
synchronized (num){
if(num.i%2==0){//若是偶数就wait
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.notify();
}
}
}
}
//输出偶数的线程
class MyThreadTwo implements Runnable{
private Num num;
public MyThreadTwo(Num number) {
this.num = number;
}
@Override
public void run() {
while (true){
synchronized (num){
if(num.i%2==1){//若是奇数就wait
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.notify();
}
}
}
}