多线程简单demo
public class Produce {
private Integer max = 10 ;
private Integer capacity = new Integer(0);
public void in(int num){
synchronized (capacity) {
while (num+capacity>max){
System.out.println("in 被阻塞 线程号:"+Thread.currentThread().getName());
try {
capacity.wait();
System.out.println(Thread.currentThread().getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("in 激活 线程号:"+Thread.currentThread().getName());
System.out.println("当前数量:" + capacity +"+"+ num);
capacity += num;
System.out.println(Thread.currentThread().getState());
capacity.notifyAll();
}
}
public void out(int num){
synchronized (capacity) {
while (num>capacity){
try {
System.out.println("out 被阻塞 线程号:"+Thread.currentThread().getName());
capacity.wait();
System.out.println(Thread.currentThread().getState());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("out 激活 线程号:"+Thread.currentThread().getName());
System.out.println("当前数量:" + capacity +"-"+ num);
capacity -= num;
capacity.notifyAll();
}
}
public static void main(String[] args) {
Produce produce = new Produce();
new Thread(new Runnable() {
@Override
public void run() {
produce.out(5);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
produce.out(3);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
produce.out(1);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
produce.in(5);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
produce.in(3);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
produce.in(1);
}
}).start();
}
}
报错内容