线程池简单使用

下面会写出几种线程池应用的示例

1.直接使用java提供的线程池类

​
class test{
	    public static void test_1() throws InterruptedException, ExecutionException{
	        //参数是线程的数量
	        ScheduledExecutorService scheduledExecutorService =Executors.newScheduledThreadPool(2);
	        //执行第一个无返回结果的任务
	        scheduledExecutorService.execute(new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("周星星");
				}
			});
	        //执行一个有返回结果的任务
	        Future submit = scheduledExecutorService.submit(new Callable() {
				@Override
				public String call() throws Exception {
					return "heiren";
				}
	        	
			});
	        System.out.println(submit.get().toString());
	        //线程阻塞2s 如果没有下面的方法 将会在 "周星星" 之前打印  "我快一点"
	        scheduledExecutorService.awaitTermination(2, TimeUnit.SECONDS);
	        
	        System.out.println("我快一点");
	        //立即关闭所有线程
	        scheduledExecutorService.shutdownNow();
	    }
	    
	    public static void main(String[] args) throws Exception {
	    	//主线程调用线程
	    	test_1();
		}
}

​

2.使用装饰者增强类

//装饰者模式
public class MyThreadPool {

	private ExecutorService executorService;

	//线程执行(无返回值)
	public void execute(Runnable command) {
		executorService.execute(command);
	}

	//线程执行(有返回值)
	public  Future submit(Callable task) {
		return executorService.submit(task);
	}
	public MyThreadPool(ExecutorService executorService) {
		//创建一个固定大小的线程池
		this.executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()-1);
	}
	//线程阻塞
	public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
		return executorService.awaitTermination(timeout, unit);
	}
	//立即关闭线程池
	public List shutdownNow() {
		return executorService.shutdownNow();
	}
	//正在执行的线程执行完成后关闭线程池
	public void shutdown() {
		executorService.shutdown();
	}
	
	
	
}
//第一个线程执行类,无返回值
class MyExecute implements Runnable{
	@Override
	public void run() {
		System.out.println("非我族类其心必异");
	}
}
//第一个线程执行类,有返回值
class MySubmit implements Callable{
	@Override
	public String call() throws Exception {
		return "人中吕布,马中赤兔";
	}
}

测试

public class test001 {
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		 ExecutorService executorService = null;
		MyThreadPool myThreadPool = new MyThreadPool(executorService);
		//执行又返回结果的线程
		Future submit = myThreadPool.submit(new MySubmit());
		String result = submit.get();
		System.out.println(result);
		//执行无返回结果的线程
		myThreadPool.execute(new MyExecute());
		//线程执行开始两秒后执行下面的代码
		myThreadPool.awaitTermination(2, TimeUnit.SECONDS);
		System.out.println("不周山");
		//关闭线程池
		myThreadPool.shutdownNow();
	}
}

运行结果:

人中吕布,马中赤兔
非我族类其心必异
不周山

 

你可能感兴趣的:(JAVA并发编程从入门到精通,线程池简单使用)