zoukankan      html  css  js  c++  java
  • 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();

    }
    }

    每一步都是一个深刻的脚印
  • 相关阅读:
    传智播客itcastbbs(二)
    传智播客itcastbbs(三)
    传智播客itcastbbs(一)(图文)
    传智播客itcastbbs(四)
    传智播客itcastbbs(六)
    双语美文:我想! 我做! 我得到!
    java邮件开发详解
    JDK_Tomcat_MyEclipse配置
    醋泡大蒜有什么功效
    优盘量产
  • 原文地址:https://www.cnblogs.com/chzlh/p/9270098.html
Copyright © 2011-2022 走看看