Java并发编程中的join()与interrupt()函数

      刚刚写了下Java的并发程序,在此做个笔记。对于线程a和b,在线程b中调用a.join(),那么此时线程b将会被挂起,直至线程a执行完才会有线程b执行的机会,若想打破这种机制,可以调用a.interrupt(),这时,线程b可以不必受刚才的约束。

 

 
  
import java.util.concurrent. * ;

class Sleeper extends Thread {
// private String name;
private int duration;

public Sleeper(String name, int duration){
super (name);
this .duration = duration;
start();
}
public void run(){
try {
System.out.println(getName()
+ " before sleep. " );
TimeUnit.MILLISECONDS.sleep(duration);
System.out.println(getName()
+ " is asleep. " );
}
catch (InterruptedException e){
System.out.println(getName()
+ " was interrupted. " + " isInterrupted(): " + isInterrupted());
return ;
}
System.out.println(getName()
+ " has awakened. " );
}
}

class Joiner extends Thread{
private Sleeper sleeper;
public Joiner(String name, Sleeper sleeper){
super (name);
this .sleeper = sleeper;
start();
}

public void run(){
try {
System.out.println(getName()
+ " before join. " );
sleeper.join();
System.out.println(getName()
+ " after join. " );
}
catch (InterruptedException e) {
System.out.println(getName()
+ " was interrupted. " );
}
System.out.println(getName()
+ " join completed. " );
}
}
public class ConcurrentBasic {
public static void main(String args[]){
Sleeper sleepy
= new Sleeper( " Sleepy " , 3000 );
Sleeper grumpy
= new Sleeper( " Grumpy " , 3000 );
Joiner dopey
= new Joiner( " Dopey " , sleepy);
Joiner doc
= new Joiner( " Doc " , grumpy);

grumpy.interrupt();

}
}

      grumpy在这被打断了,那么和它join的doc将会被唤醒,从而导致doc线程的执行,这里可以把grumpy.interrupt()改为doc.interrupt(),运行情况与预想差不多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值