首页 > 代码库 > java多线程总结三:sleep()、join()、interrupt()示例
java多线程总结三:sleep()、join()、interrupt()示例
这是一个来自《java编程思想上的示例》
[java] view plaincopy
- package demo.thread;
- /**
- *sleep()是静态方法,是属于类的,作用是让当前线程阻塞
- *join()是使线程同步,如在某个线程里调用t.join()表示t线程执行完再执行当前线程
- *interrupt()给线程设定一个标志表示该线程已被中断,但在异常捕获时将清理这个标志
- *所以在catch子句中,该标志为false
- */
- public class SleepJoinDemo {
- public static void main(String[] args) {
- Sleeper sleep1 = new Sleeper("sleep1", 1500);
- Sleeper sleep2 = new Sleeper("sleep2", 1500);
- Joiner join1 = new Joiner("join1", sleep1);
- Joiner join2 = new Joiner("join2", sleep1);
- sleep2.interrupt();
- }
- }
- class Sleeper extends Thread {
- // 可以传参设定睡眠时间
- private int sleepTime;
- public Sleeper(String name, int sleepTime) {
- super(name);
- this.sleepTime = sleepTime;
- start();// 在构造方法中启动
- }
- @Override
- public void run() {
- try {
- sleep(sleepTime);
- } catch (InterruptedException e) {
- System.out.println(getName() + " was interrupted.\n"
- + "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 {
- sleeper.join();//合并,异步变同步
- } catch (InterruptedException e) {
- System.out.println("interrupted");
- }
- System.out.println(getName() + " join completed");
- }
- }
java多线程总结三:sleep()、join()、interrupt()示例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。