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中终止正在运行线程的主要内容,如果未能解决你的问题,请参考以下文章