java多线程总结

把同步锁加在代码段上。确切的说,是把同步锁加在“访问共享资源的代码段。

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//通过Callable接口创建MyCallable
//<String>里写的是MYcallable线程的名字
public class MyCallable implements Callable<String> {
	private String name;
public MyCallable(String name){
	this.name=name;
}

	@Override
	public String call() throws Exception {
		// TODO Auto-generated method stub
		return name;
	}
	//创建一个大小为5的线程池
	ExecutorService pool =Executors.newFixedThreadPool(5);
//   创建多个有返回值的任务列表List
	ArrayList<Future> List=new ArrayList<Future>();
	public void run() throws InterruptedException, ExecutionException{
		Future future0 =pool.submit(this);
		System.out.println("submit a callable thread:"+name);
		List.add(future0);
	for(int i=0;i<5;i++){
//		创建一个有返回值的线程实例
		Callable c=new MyCallable(i+"");
//		提交线程,获取Future对象并将其保存到Future List中
		Future future =pool.submit(c);
		//submit执行线程任务
		System.out.println("submit a callable thread:"+i);
		List.add(future);
	}
	
//	关闭线程 等待线程执行结束
	pool.shutdown();
//	遍历所有线程的运行结果
	for (Future future :List){
//		从Future对象上获取任务的返回值,并将结果输出到控制台
		System.out.println("get the result from callable thread:"+future.get().toString());

	}
	
}}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值