52、java.util.concurrent練習
3963 ワード
import java.util.concurrent.*;
public class ExecutorsTest
{
public static void main(String[] args)
{
//ExecutorService threadPool = Executors.newFixedThreadPool(3);//
//ExecutorService threadPool = Executors.newCachedThreadPool();//
ExecutorService threadPool = Executors.newSingleThreadExecutor();// , : 。 ,
for(int i=0;i<10;i++)
{
final int task = i+1;
threadPool.execute(new Runnable(){
public void run()
{
for(int j=0;j<10;j++)
System.out.println(Thread.currentThread().getName()+" loop of "+(j+1)+" task of "+task);
}
});
}
threadPool.shutdown();//
System.out.println("all of 10 tasks have committed");
}
}
import java.util.concurrent.*;
public class ExecutorsTest
{
public static void main(String[] args)
{
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3);
/*threadPool.schedule(new Runnable(){
public void run()
{
System.out.println(Thread.currentThread().getName()+" bombing");
}
},
2,
TimeUnit.SECONDS);
thradPool.shutdown();
*/
threadPool.scheduleAtFixedRate(new Runnable(){
public void run()
{
System.out.println("bombing");
}
},
2,
1,
TimeUnit.SECONDS);
}
}
import java.util.concurrent.*;
public class ExecutorsTest
{
public static void main(String[] args)
{
ExecutorService threadPool = Executors.newFixedThreadPool(3);
Future<Integer> future = threadPool.submit(new Callable<Integer>(){
public Integer call()throws Exception
{
System.out.println(Thread.currentThread().getName());
Thread.sleep(2000);
return 3;
}
});
try{
System.out.println("main thread is coming");
Integer res = future.get();//get()
System.out.println(res);
}catch(Exception e){}
threadPool.shutdown();
}
}
import java.util.concurrent.*;
import java.util.*;
public class ExecutorsTest
{
public static void main(String[] args)
{
ExecutorService threadPool = Executors.newFixedThreadPool(3);
Collection<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
Callable<Integer> task1 = new Callable<Integer>(){
public Integer call()throws Exception
{
System.out.println(Thread.currentThread().getName()+" task 1");
Thread.sleep(2000);
return 111111;
}
};
Callable<Integer> task2 = new Callable<Integer>(){
public Integer call()throws Exception
{
System.out.println(Thread.currentThread().getName()+" task 2");
Thread.sleep(2000);
return 222222;
}
};
Callable<Integer> task3 = new Callable<Integer>(){
public Integer call()throws Exception
{
System.out.println(Thread.currentThread().getName()+" task 3");
Thread.sleep(2000);
return 333333;
}
};
tasks.add(task1);
tasks.add(task2);
tasks.add(task3);
System.out.println(tasks);
try{
List<Future<Integer>> retval = threadPool.invokeAll(tasks);//
for(int i=0;i<retval.size();i++)
{
Integer res = retval.get(i).get();//get()
System.out.println(res);
}
}catch(Exception e){}
threadPool.shutdown();
}
}