无上下文在线程之间切换

时间:2016-03-04 22:04:30

标签: java multithreading producer-consumer

我正在尝试使用wait和notify实现生产者消费者问题。 问题在于,生产者首先生产一切,然后消费者开始消费。我是多线程环境的新手。

请在下面找到我的代码:

package javaExamples;

import java.util.ArrayList;
import java.util.List;

public class producerConsumerWaitNotifyMain {

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>();
        int size = 50;
        ProducerWait prod = new ProducerWait(list, size);
        ConsumerWait cons = new ConsumerWait(list, size);
        Thread pro = new Thread(prod);
        Thread con = new Thread(cons);
        pro.start();
        con.start();
    }

}

*****************************

package javaExamples;

import java.util.List;

public class ProducerWait implements Runnable{
    List<Integer> list;
    int size;

    public ProducerWait(List<Integer> list, int size) {
        this.list = list;
        this.size = size;
    }

    @Override
    public void run() {
        while(true){
        synchronized(list){

                if(list.size() == size){
                    try {
                        System.out.println("Producer waiting");
                        System.out.println(list);
                        list.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                else{
                    System.out.println("producer will produce");
                    list.add(1);
                    System.out.println(list);
                    list.notifyAll();
                }
            }
        }

    }

}

***********************************


package javaExamples;

import java.util.List;

public class ConsumerWait implements Runnable{
    List<Integer> list;
    int size;

    public ConsumerWait(List<Integer> list, int size) {
        this.list = list;
        this.size = size;
    }

    @Override
    public void run() {
        while(true){
        synchronized(list){

                if(list.isEmpty()){
                    try {
                        System.out.println("Consumer waiting");
                        System.out.println(list);
                        list.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                else{
                    System.out.println("consumer will consume");
                    list.remove(0);
                    System.out.println(list);
                    list.notifyAll();
                }
            }
        }

    }

}

0 个答案:

没有答案