Java 中中止线程
范例
public class Main{
static volatile boolean exit = false;
public static void main(String[] args){
System.out.println("Starting the main thread");
new Thread(){
public void run(){
System.out.println("Starting the inner thread");
while (!exit){
}
System.out.println("Exiting the inner thread");
}
}.start();
try{
Thread.sleep(100);
}
catch (InterruptedException e){
System.out.println("Exception caught :" + e);
}
exit = true;
System.out.println("Exiting main thread");
}
}输出
Starting the main thread Starting the inner thread Exiting main thread Exiting the inner thread
主类创建一个新线程,并调用它的“run”函数。在此,定义了一个名为“exit”的布尔值,最初设置为 false。在 while 循环外部,调用了“start”函数。在 try 块中,新创建的线程休眠特定时间,此后会捕获异常,并且相关消息会显示在屏幕上。在此之后,主线程将退出,因为 exit 的值将设置为“true”。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP