zoukankan      html  css  js  c++  java
  • Java 多线程之 等待唤醒机制

    等待唤醒机制 (同步锁中 使各个线程能有效的利用资源)

    public class Resource { //锁类

    public String name;

    public int age;

    public boolean flag=false;//标记  true赋值完成  ,false输出完成

    }

    public class Input implements Runnable{ //输入任务类

    private Resource r;

    public Input(){}

    public Input(Resource r){ this.r=r; } //有参构造

    public void run() {

    int i=0;

    while(true){ //复制完(true) 等  输出完(false)赋值

    synchronized (r){ //同步代码块(锁对象)

    if(r.flag){ r.wait();//try...catch } //.等待(线程暂停)

    if(i%2==0){ r.name="张三";  r.age=18; }//没改完就获取了

    else{ r.name="李四";  r.age=19; }

    r.flag=true;

    r.notify(); //.唤醒(随机唤一锁)

    } //r.notifyAll(); 唤醒线程池中所有wait() 线程

    i++;

    }

    }

    }

    public class Output implements Runnable{ //输出任务类

    private Resource r;

    public Output(){}

    public Output(Resource r){this.r=r;}

    public void run() {

    //Resource进行输出

    while(true){

    synchronized(r){

    if(!r.flag){ r.wait();//try...catch }

    System.out.println(r.name+"..."+r.age);

    r.flag=false;

    r.notify();

    }

    }

    }

    }

    public class TestResource {//等待唤醒机制

    public static void main(String[] args) {

    Resource r=new Resource(); //

    Input in=new Input(r); //任务共用一把锁

    Output out=new Output(r);

    Thread t1=new Thread(in);

    Thread t2=new Thread(out);

    t1.start();

    t2.start();//IllegalMonitorStateException  无效监视器异常

    }

    }

  • 相关阅读:
    angularJS 数组更新时重新排序之解决方案一:这个坑,绕开吧,不跳了……
    移动web开发之rem响应式设计
    IIS wAS机制
    触摸方法
    滑动加载函数
    js有关数组的函数
    用absolute进行页面的自适应布局
    absolute
    清除float的方法
    图片和文字的位置垂直居中和左右摆放
  • 原文地址:https://www.cnblogs.com/javscr/p/10251093.html
Copyright © 2011-2022 走看看