• java多线程(线程通信-等待换新机制-代码优化)


    等待唤醒机制涉及方法:

    wait():让线程处于冻结状态,被wait的线程会被存储到线程池中。

    noticfy():唤醒同一个线程池中一个线程(任意也可能是当前wait的线程)

    notifyAll():唤醒同一个线程池中所有的线程。

    这些方法必须定义在同步中,因为这个方法是用于操作线程状态的方法,必须要明确到地操作的是哪个锁上的线程。

    为什么操作线程的方法wait,notify,notifyAll定义在object类中。

    因为这些方法是监视器(锁)方法,监视器是锁。

    锁是任意对象,任意对象调用的方法就在Object类中。

    class Resource{

    private String name;
    private String sex;
    private boolean flag = false;

    public synchronized void set(String name ,String sex){
    if(flag){
    try{wait();}catch(Exception e){}
    }
    notify();
    this.name = name;
    this.sex = sex;
    System.out.println(this.name+"**input*"+this.sex);
    flag = true;

    }
    public synchronized void out(){
    if(!flag){
    try{wait();}catch(Exception e){}
    }
    notify();
    System.out.println(this.name+"**output*"+this.sex);
    flag = false;

    }
    }

    class Input implements Runnable {
    Resource s ;
    Input(Resource t){
    this.s = t;
    }
    int i = 0;
    public void run (){
    while(true){
    if(i ==0){
    s.set("mike","man");
    }else{
    s.set("xixi","women");
    }
    i= (i+1) % 2;
    }
    }
    }
    class Output implements Runnable{
    Resource s;
    Output(Resource t){
    this.s = t;
    }
    public void run(){
    while(true){
    s.out();
    }
    }

    }

    class ResourceDemo{
    public static void main(String[] arg){
    Resource s = new Resource();

    Input p = new Input(s);
    Output o = new Output(s);

    Thread t1 = new Thread(p);
    Thread t2 = new Thread(o);

    t1.start();
    t2.start();

    }
    }

    每一步都是一个深刻的脚印
  • 相关阅读:
    javascript运动详解
    jQuery Ajax封装通用类 (linjq)
    Bootstrap 字体图标引用示例
    jQuery $.each用法
    jquery中odd和even选择器的用法说明
    JQuery中怎么设置class
    HTML5中input背景提示文字(placeholder)的CSS美化
    边框上下左右各部位隐藏显示详解
    纯CSS气泡框实现方法探究
    对比Tornado和Twisted两种异步Python框架
  • 原文地址:https://www.cnblogs.com/chzlh/p/9270098.html
Copyright © 2020-2023  润新知