【发布时间】:2017-08-08 13:45:54
【问题描述】:
public class Queue {
int value = 0;
boolean isEmpty = true;
public synchronized void put(int n){
if (!isEmpty){
try {
System.out.println("producer is waiting");
wait();
}catch (Exception e){
e.printStackTrace();
}
}
value += n;
isEmpty = false;
System.out.println("The number of products:"+value);
notifyAll();
}
public synchronized void get(){
if (isEmpty){
try{
System.out.println("customer is waiting");
wait();
}catch (Exception e){
e.printStackTrace();
}
}
value --;
if(value<1){
isEmpty = true;
}
System.out.println("there are "+value+" left");
notifyAll();
}
}
public class Producer extends Thread{
private Queue queue;
public Producer(String name,Queue queue){
super(name);
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
queue.put(i+1);
}
}
}
public class Producer extends Thread{
private Queue queue;
public Producer(String name,Queue queue){
super(name);
this.queue = queue;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
queue.put(i+1);
}
}
}
public class Main {
public static void main(String[] args) {
Queue queue = new Queue();
Thread customer1 = new Customer("customer1",queue);
Thread producer1 = new Producer("producer1",queue);
customer1.setPriority(4);
producer1.setPriority(7);
producer1.start();
customer1.start();
}
}
输出:
产品数量:1 生产者在等待 还有0left 客户在等待 产品数量:2 生产者在等待 有 1 个 还有0left 客户在等待 产品数量:3 生产者在等待 有2个 有 1 个 还有0left 客户在等待 产品数量:4 生产者在等待 有3个 有2个 有 1 个 还有0left 客户在等待 产品数量:5 有4个 有3个 有2个 有 1 个 还有0left 客户在等待我不知道为什么输出的顺序是这样的。
为什么不像
那样输出结果 产品数量:3 生产者在等待 有2个 产品数量:6 有5个 产品数量:10 剩下9个 产品数量:15 还有14个【问题讨论】:
-
为什么需要多线程?
-
我只是想知道为什么它不能这样工作。
-
无法保证进程同步。
-
总是输出一样的东西,顺序没有变化。
-
您的生产者将 15 个“项目”放入队列中。这是你的意图吗?
标签: java multithreading