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();