要求
使用生产者和消费者模式实现,交替输出:
假设只有两个线程,输出以下结果:
t1-->1
t2-->2
t1-->3
t2-->4
t1-->5
t2-->6
....要求:必须交替,并且t1线程负责输出奇数。t2线程负责输出偶数。
两个线程共享一个数字,每个线程执行时都要对这个数字进行:++
代码实现
public class OddEven02 {
public static void main(String[] args) {
Num1 num = new Num1(99);
Thread th1 = new Thread(new Odd1(num),"奇数线程");
Thread th2 = new Thread(new Even1(num),"偶数线程");
th1.start();
th2.start();
}
}
// 奇数线程
class Odd1 implements Runnable{
private Num1 num;
public Odd1() {
}
public Odd1(Num1 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();
}
}
try {
Thread.sleep(1000*1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--->" + num.i++);
num.notify();
}
}
}
}
// 偶数线程
class Even1 implements Runnable{
private Num1 num;
public Even1() {
}
public Even1(Num1 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();
}
}
try {
Thread.sleep(1000*1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--->" + num.i++);
num.notify();
}
}
}
}
// 数字类
class Num1{
int i;
public Num1(int i) {
this.i = i;
}
}