Java使用notify()、wait()、和notifyAll()来进行线程间的通信

1、notify()、wait()、和notifyAll()方法是由object类实现的因此这几个方法是所有对象的一部分

wait()使线程等待直到有notify()

2、基本形式:

final void wait() throws InterruptedException  //等待直到被通知

final void wait(long millis) throws InterruptedException  //等待直到被通知或者直到经过以毫秒为单位指定的millis 周期

final void wait(long millis,int nanos) throws InterruptedException //以纳秒为单位指定等待周期

final void notify() //恢复一个等待中的线程

final void notifyAll()// 通知所有的线程 然后具有最高优先级的获得资源


class TickTock 
{
String state;//设置标志 "Tick" or "Tock"
synchronized void tick(boolean running){
if(!running){//stop the clock
state = "ticked";
notify(); //notify any waiting thread
return ;
}
System.out.print("Tick");

//let tock() run  tick()通知tock();
try
{
state = "ticked";
Thread.sleep(500);
notify();
while (!state.equals("tocked"))
{
wait();//wait for tock() to complete  tick()等待tock();
}
}
catch (InterruptedException exc)
{
System.out.println("Thread interrupted!");
}
  }




  synchronized void tock(boolean running){
if(!running){
state = "tocked";
notify(); //notify any waiting thread
return ;
}
System.out.println("Tock");


try
{
state = "tocked";
Thread.sleep(500);
notify();//let tock() run 
while (!state.equals("ticked"))
{
wait();//wait for tick() to complete
}
}
catch (InterruptedException exc)
{
System.out.println("Thread interrupted!");
}
  }


}


class MyThread implements Runnable
{
Thread thrd;
TickTock ttob;
MyThread(String name,TickTock tt){
thrd = new Thread(this,name);
ttob = tt;
thrd.start();//start the thread
}
public void run(){
if (thrd.getName().compareTo("Tick") == 0)
{
for (int i=0; i<5 ; i++ )
{
ttob.tick(true);

}
ttob.tick(false);
}
else
{
for (int i=0; i<5 ; i++ )
{
ttob.tock(true);

}
ttob.tock(false);
}
}
}


class ThreadCom
{
public static void main(String[] args) 
{
TickTock tt = new TickTock();
MyThread mt1 = new MyThread("Tick",tt);
MyThread mt2 = new MyThread("Tock",tt);


try
{
mt1.thrd.join();
mt2.thrd.join();
}
catch (InterruptedException exc)
{
System.out.println("异常中断!");
}
System.out.println("主线程停止");
}
}


//当执行Tick()时,显示单词Tick 并且把state设置为"Ticked",然后调用modify()之后通知其他线程
//然后调用了wait()使得自己挂起。直到tock()调用notify()并且把自己挂起



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值