把同步锁加在代码段上。确切的说,是把同步锁加在“访问共享资源的代码段。
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());
}
}}