本帖最后由 杜光 于 2013-8-4 10:06 编辑
- package qbb;
- class Resource {
- private String name;
- private int no = 1;
- private boolean flag = false;
- public synchronized void produce(String name) {
- if(flag) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- this.name = name + "---" + no++;
- System.out.println(Thread.currentThread().getName() +
- "---生产者: " + this.name);
- flag = true;
- notify();
- }
- public synchronized void consume() {
- if(!flag) {
- try {
- wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.println(Thread.currentThread().getName() +
- "---消费者----: " + name);
- flag = false;
- notify();
- }
- }
- class Producer implements Runnable {
- private Resource r;
- Producer(Resource r) {
- this.r = r;
- }
- public void run() {
- while(true) {
- r.produce("商品");
- }
- }
- }
- class Consumer implements Runnable {
- private Resource r;
- Consumer(Resource r) {
- this.r = r;
- }
- public void run() {
- while(true) {
- r.consume();
- }
- }
- }
- public class ProducerConsumer {
- public static void main(String[] args) {
- Resource res = new Resource();
- Producer pro = new Producer(res);
- Consumer con = new Consumer(res);
- Thread t1 = new Thread(pro);
- Thread t2 = new Thread(pro);
- Thread t3 = new Thread(con);
- Thread t4 = new Thread(con);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码 运行结果会出现以下片段:
Thread-2---消费者----: 商品---477219 Thread-3---消费者----: 商品---477219 Thread-2---消费者----: 商品---477219 Thread-3---消费者----: 商品---477219 Thread-2---消费者----: 商品---477219 怎么解释呢?线程间怎么切换才能出现这种结果呢?
|