多线程测试代码

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yangyongdehao30/article/details/79326821

package com.yy.read;




import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
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;


public class Test {

//开启10个线程 执行
static ExecutorService es =Executors.newFixedThreadPool(6);


public static void main(String[] args) throws Exception {
//并发请求1
new Thread(new Runnable() {
@Override
public void run() {
try {
dobussiness("A","B");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
//并发请求2
new Thread(new Runnable() {
@Override
public void run() {
try {
dobussiness("C","D");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
//并发请求3
new Thread(new Runnable() {
@Override
public void run() {
try {
dobussiness("E","F");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();


}


private static void dobussiness(String taskAName,String taskBName) throws InterruptedException, ExecutionException {
//同步多线程
Callable<String> taskA= getnewCallable(taskAName);
Callable<String> taskB = getnewCallable(taskBName);



Set<Callable<String>> tasks  = new HashSet<>();
tasks.add(taskA);
tasks.add(taskB);

//执行所有的callable
List<Future<String>> list=es.invokeAll(tasks);

for (Future<String> future : list) {
if(!future.isDone())
throw new RuntimeException(future.get()+"尚未完成");

System.out.println("处理结果:"+future.get());

}
}


public static Callable<String> getnewCallable(String taskName) {
return new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println(Thread.currentThread().getName() + "执行任务"+taskName);
int i = new Random().nextInt(10) ;
System.out.println("处理["+i+"]秒");
Thread.currentThread().sleep(i* 1000);
System.out.println("处理["+i+"]秒结束");
return Thread.currentThread().getName();
}
};


}
}

猜你喜欢

转载自blog.csdn.net/yangyongdehao30/article/details/79326821