Java多线程学习之线程组、线程池的使用

线程组

Java中使用ThreadGroup来表示线程组,可以对一批线程进行分类管理。

package thread;

public class MyRunnable implements Runnable {
	@Override
	public void run() {
		for(int i = 0; i < 100; i++){
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
	}
}
package thread;

public class ThreadGroupDemo {
	public static void main(String[] args) {
		//method1();
		method2();
	}

	private static void method2() {
		//创建一个线程组
		ThreadGroup tg = new ThreadGroup("不是main");
		
		MyRunnable my = new MyRunnable();
		//线程创建时指定所属线程组
		Thread t1 = new Thread(tg,my,"t1");
		Thread t2 = new Thread(tg,my,"t2");
		
		System.out.println("t1"+t1.getThreadGroup().getName()+"----"+"t2"+t2.getThreadGroup().getName());
		
		//通过线程组操作所有线程
		//tg.setDaemon(true);
	}

	private static void method1() {
		MyRunnable my = new MyRunnable();
		Thread t1 = new Thread(my,"t1");
		Thread t2 = new Thread(my,"t2");
		
		ThreadGroup tg1 = t1.getThreadGroup();
		ThreadGroup tg2 = t2.getThreadGroup();
		//线程默认情况下是属于main线程组
		System.out.println("t1"+tg1.getName()+"----"+"t2"+tg2.getName());
	}
}

线程池

线程池里的每一个线程代码结束后,并不会死亡,而是再次回到线程池中成为空闲状态,等待下一个对象来使用。

Executors工厂类来产生线程池

public static ExecutorService newFixedThreadPool(int nThreads)

返回值是ExecutorService对象,表示一个线程池,可以执行Runnable对象或者Callable对象的线程。

Future<?> submit(Runnable task)

package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorsDemo {
	public static void main(String[] args) {
		//创建一个线程池对象,控制要创建几个线程对象
		ExecutorService pool = Executors.newFixedThreadPool(2);
		
		//可以执行Runnable对象或者Callable对象代表的线程
		pool.submit(new MyRunnable());
		pool.submit(new MyRunnable());
		
		//结束线程池
		pool.shutdown();
	}
}

猜你喜欢

转载自blog.csdn.net/weufengwangshi_/article/details/81676135