码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-07-05 21:42:27      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:ati   nts   static   java多线程   source   not   object类   out   存储   

等待唤醒机制涉及方法:

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();

}
}

 

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

标签:ati   nts   static   java多线程   source   not   object类   out   存储   

原文地址:https://www.cnblogs.com/chzlh/p/9270098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!