线程实例分析

文章链接:http://www.liuschen.com

如果在主线程中启动一个子线程,将这个子线程join到主线程上,子线程中再开一个线程池来启动一个新的任务。这个新的任务中设置一个无限循环。当程序执行5分钟后,有多少线程还在执行。程序如下:

public class Main {
	public static void main(String[] args){
		try {
		Thread thread;
		thread = new Thread(){
			 @Override
			public void run() {
				 ExecutorService fixPool = Executors.newFixedThreadPool(5);
				 WorkRunable1 runa = new WorkRunable1();
				 //WorkRunable1 runa2 = new WorkRunable1();
				 fixPool.execute(runa);
				 //fixPool.execute(runa2);
				 System.out.println("该线程已经执行完毕:当前线程为"+Thread.currentThread().getName());
			}
		};
		thread.start();
		thread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("主线程已经执行完毕:"+Thread.currentThread().getName());
		
	}
	
	public static class WorkRunable1 implements Runnable{

		@Override
		public void run() {
			while(true){
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("我一直在输出:"+Thread.activeCount());
			}
		}
		
	}
}

执行显示将会有两个线程:

Thread[pool-1-thread-1]
Thread[DestoryJavaVM]

这时,第一个启动的子线程早已经结束,所以main线程也随之结束。但是,还有线程执行,在主线程结束后启动了DestoryJavaVM,监听是否还有非守护线程执行,如果没有将关闭JVM。

如果在一个子线程中开一个无限循环,那么执行的线程将会变为2个,分别是:

主线程,第一个启动的子线程,和持续输出的线程池中的线程。

Loading Disqus comments...
Table of Contents