首页 > 代码库 > Java中终止正在运行线程

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中终止正在运行线程