当前位置 : 主页 > 编程语言 > java >

Java并发编程核心_如何关闭一个线程

来源:互联网 收集:自由互联 发布时间:2022-07-04
捕获中断信号关闭线程 package com . neu . day02 ; import java . util . concurrent . TimeUnit ; /** * @Author yqq * @Date 2022/03/27 18:50 * @Version 1.0 */ public class Thread05 { public static void main ( String [] args ) throws I

捕获中断信号关闭线程

package com.neu.day02;

import java.util.concurrent.TimeUnit;

/**
* @Author yqq
* @Date 2022/03/27 18:50
* @Version 1.0
*/
public class Thread05 {
public static void main(String[] args) throws InterruptedException{
Thread t = new Thread(){
@Override
public void run() {
System.out.println("I will start work.");
while (!this.isInterrupted()){
System.out.println("I an working");
}
System.out.println("I will be exiting");
}
};
t.start();
TimeUnit.SECONDS.sleep(5);
System.out.println("System will be shutdown");
t.interrupt();
}
}

Java并发编程核心_如何关闭一个线程_ide

使用 volatile 开关控制

package com.neu.day02;

import java.util.concurrent.TimeUnit;

/**
* @Author yqq
* @Date 2022/03/27 19:02
* @Version 1.0
*/
public class Thread06 {
public static void main(String[] args) throws InterruptedException{
Mytask t = new Mytask();
t.start();
TimeUnit.SECONDS.sleep(5);
System.out.println("System will be shutdown");
t.close();
}
}

class Mytask extends Thread{

private volatile boolean closed = false;

@Override
public void run() {
System.out.println("I will start work.");
while (!closed && isInterrupted()){
System.out.println("I an working");
}
System.out.println("I will be exiting");
}
public void close(){
this.closed = true;
this.interrupt();
}
}

Java并发编程核心_如何关闭一个线程_mysql_02


上一篇:面试题-Java基础篇(1)
下一篇:没有了
网友评论