线程池demo

package test;

import java.util.ArrayList;
import java.util.List;
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 Test1 {
public static void main(String[] args) {
test2();
} public static void test1(){
int count = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(count); A a = new A(); try {
for(int i = 0;i<count;i++){
service.execute(a);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(!service.isShutdown()){
service.shutdown();
}
}
} public static void test2(){
int count = Runtime.getRuntime().availableProcessors();
ExecutorService service = Executors.newFixedThreadPool(count); B b = new B(); List<Future<String>> list = new ArrayList<Future<String>>();
try {
for(int i = 0;i<count;i++){
Future<String> f = service.submit(b);
list.add(f);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if(!service.isShutdown()){
service.shutdown();
}
} try {
String a = list.get(0).get();
System.out.println("a:"+a);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} System.out.println("next"); }
} class B implements Callable<String>{ @Override
public String call() throws Exception {
String a = "call";
Thread.sleep(10000);
System.out.println(a);
return a;
} }
class A implements Runnable {
private int ticketNum = 1;
private Object o = new Object(); @Override
public void run() { while(true){ synchronized (o) {
if(ticketNum>500000){
break;
} System.out.println(Thread.currentThread().getName()+"出售了第"+ticketNum+"张票"); ticketNum++;
} } } }
上一篇:tensorflow进阶篇-5(反向传播1)


下一篇:bash的基础特性