package com.study.Java;
class Produces implements Runnable {
private int Num;
private Object OLock = new Object();
private Object TLock = new Object();
public static int Choice = 1;
@Override
public void run() {
if (Choice == 1) {
while (true) {
synchronized (OLock) {
try {
Num = Num + 1;
System.out.println(Thread.currentThread().getName()
+ "生产产品,产品数目为:" + Num);
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
if (Choice == 0) {
while (true) {
synchronized (TLock) {
try {
Thread.sleep(1000);
Num = Num - 1;
System.out.println(Thread.currentThread().getName()
+ "消耗产品,产品剩余数目为:" + Num);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static void Switch() {
Choice = 0;
}
}
public class MulitThread {
public static void main(String[] args) {
Produces produces = new Produces();
Thread producer1 = new Thread(produces, "生产者1号");
producer1.start();
//代码1
Thread consumer1 = new Thread(produces, "消费者1号");
consumer1.start();
Produces.Switch();
}
}
生产者在chocie=1的区域运行,消费者在choice=0的区域运行
为什么将Produces.Switch();放到最后才实现到,而放在 代码1 区域就不行。请问为什么!!?
|
|