zoukankan      html  css  js  c++  java
  • 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(),运行情况与预想差不多。

    ---
    可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明
  • 相关阅读:
    #Bug--Mapper资源加载不到
    Spring项目用JUnit调试时出现错误 Failed to load ApplicationContext 的解决方法
    安装和配置maven遇到的坑
    DataGrip 异常
    数据库-1055报错-把only_full_group_by去掉
    spring boot 配置logback.xml 日志重复打印
    eclipse创建maven项目
    【C++11新特性】 C++11智能指针之weak_ptr
    socket编程中的粘包问题解决方案
    c++的反映机制实现
  • 原文地址:https://www.cnblogs.com/null00/p/2065090.html
Copyright © 2011-2022 走看看