Java中终止正在运行线程

Posted 牧羊人的世界

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java中终止正在运行线程相关的知识,希望对你有一定的参考价值。

问题:java 中如何让一个正在运行的线程终止掉?

Demo_1:

class TT implements Runnable {
	private boolean flag = true;
	@Override
	public void run() {
		int i = 0;
		while(flag) {
			System.out.println("child thread: "+i++);
		}
	}
	public void shutDowm() {
		flag = false;
	}
}
class TestThread {
	public static void main(String[] args) {
		TT tt = new TT();
		Thread t = new Thread(tt);
		t.start();
		for(int i = 0; i < 4; i++) {
			System.out.println("the main Thread is running : "+i);
		}
		System.out.println("Thread main is void");
		tt.shutDowm();
	}
}

Demo_2:

class TT implements Runnable {
	@Override
	public void run() {
		for(int i = 1; i <= 589; i++){
			System.out.println("subThread: "+ i);
		}
	}
}
class TestThread {
	public static void main(String[] args) {
		TT tt = new TT();
		Thread t = new Thread(tt);
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
		}
		for(int i = 0; i < 8; i++) {
			System.out.println("main Thread is running : "+i);
		}
	}
}

Demo_3:

class TT extends Thread {
	@Override
	public void run() {
		for(int i = 1; i <= 5; i++){
			System.out.println("subThread: "+ i);
		}
	}
}
class TestThread {
	public static void main(String[] args) {
		TT tt = new TT();
		tt.start();
		
		Thread dd = new TT();
		dd.start();
		for(int i = 0; i < 8; i++) {
			System.out.println("main Thread is running : "+i);
		}
	}
}

 运行结果:

main Thread is running : 0
main Thread is running : 1
main Thread is running : 2
subThread: 1
subThread: 1
subThread: 2
subThread: 2
main Thread is running : 3
main Thread is running : 4
main Thread is running : 5
main Thread is running : 6
main Thread is running : 7
subThread: 3
subThread: 4
subThread: 5
subThread: 3
subThread: 4
subThread: 5


















以上是关于Java中终止正在运行线程的主要内容,如果未能解决你的问题,请参考以下文章

在片段活动中显示自定义对话框

java线程池中正在执行的线程彻底停止

java中终止程序的执行

[编程][JAVA]在JAVA中如何终止线程中socket.accpet() ? 端口一直被占用

在 CANBus 适配器的隐藏代码中终止线程

Java--终止/中断线程