b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

java多线程死锁 moira33的博客(6)

电脑杂谈  发布时间:2017-12-25 23:02:18  来源:网络整理
public class InputOutputDemo2 {
    public static void main(String[] args) {
        Res r = new Res();
        new Thread(new Input(r)).start();
        //用匿名对象简化代码,因为只调用该对象的一个方法--start方法--一次
        new Thread(new Output(r)).start();
        /*
        Input in = new Input(r);
        Output out = new Output(r);
        Thread t1 = new Thread(in);
        Thread t2 = new Thread(out);
        t1.start();
        t2.start();
        */
    }
}

结果:

SET】丽丽1女
【OUT】丽丽1女
【SET】丽丽2女
【OUT】丽丽2女
【SET】丽丽3女
【OUT】丽丽3女
【SET】丽丽4女
【OUT】丽丽4女
【SET】丽丽5女
【OUT】丽丽5

对于多个生产者和消费者,为什么要定义while判断标记。

原因:让被唤醒的线程再一次判断标记。

为什么定义notifyAll:需要唤醒对方线程。只用notify,容易出现只唤醒本方线程的情况。导致程序中的所有线程都等待。

public class ProducerConsumerDemo {
    public static void main(String[] args) {
        Resource r = new Resource();
        new Thread(new Producer(r)).start();
        new Thread(new Producer(r)).start();
        new Thread(new Consumer(r)).start();
        new Thread(new Consumer(r)).start();
    }
}

class Resource {
    private String name;
    private int count = 1; //为商品编号
    private boolean flag = false;

    //  t1    t2
    public synchronized void set(String name) {
        while (flag) {
            //如果用if,线程判断完如停在这儿等再被唤醒就不再判断直接向下运行
            try {
                this.wait();
            } catch (Exception e) {
            } //t1(放弃资格)  t2(获取资格)
        }
        this.name = name + "--" + count++;
        System.out.println(Thread.currentThread().getName() + "...生产者.." + this.name);
        flag = true;
        this.notifyAll();
    }

    //  t3   t4  
    public synchronized void out() {
        while (!flag) {
            try {
                wait();
            } catch (Exception e) {
            } //t3(放弃资格) t4(放弃资格)
        }
        System.out.println(Thread.currentThread().getName() + "...消费者........." + this.name);
        flag = false;
        this.notifyAll();
    }
}

class Producer implements Runnable {
    private Resource res;

    Producer(Resource res) {
        this.res = res;
    }

    public void run() {
        while (true) {
            res.set("+商品+");
        }
    }
}

class Consumer implements Runnable {
    private Resource res;

    Consumer(Resource res) {
        this.res = res;
    }

    public void run() {
        while (true) {
            res.out();
        }
    }
}


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-55883-6.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    • 周杏
      周杏

      就算你唱歌好听那你也是一个没人知道的路人

    • 文宣帝高洋
      文宣帝高洋

      只是为利益的流氓而已

    热点图片
    拼命载入中...