java并发编程——ExecutorService\join\yield
2016-01-23 23:29
344 查看
Thread.yield():
package com.concurrent.warmingUp; public class LiftOff implements Runnable { protected int countDown = 10; private static int taskCount = 0; private final int id = taskCount++; public LiftOff(int countDown) { this.countDown = countDown; } public LiftOff() { } public String status() { return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "),"; } @Override public void run() { while (countDown-- > 0) { System.out.print(status()); // Thread.yield() 对线程调度器的建议,建议 // 引发上下文切换:"当前this线程已经执行到某处,可以切换上下文了,让给其他线程" // Thread.yield() 不一定保证执行 // Thread.yield(); try {// run方法中必须被捕获,因为异常不可以跨线程捕获,一个线程中的异常无法逃逸出当前线程 Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) { for (int i = 0; i < 5; i++) { // 每个Thread都注册了自己,GC在start执行完之前,不会对线程做回收 new Thread(new LiftOff()).start(); } } }
Callable
Runnable的Run方法是void类型,当我们需要任务有返回值时使用Callable:class TaskWithResult implements Callable<String> { private int id; public TaskWithResult(int id) { this.id = id; } @Override public String call() throws Exception { return "result of TaskWithResult#" + id; } } public class CallableDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService exec = Executors.newCachedThreadPool(); // Future代表一个将要异步执行的任务,a Future representing pending completion of the // task List<Future<String>> results = new ArrayList<Future<String>>(); for (int i = 0; i < 100; i++) { results.add(exec.submit(new TaskWithResult(i))); } for (Future<String> fs : results) { // get() blocks until completion try { System.out.println(fs.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally { exec.shutdown(); } } } }
线程池
物理上,创建线程的代价是较高的,所以我们应该保存并管理它。主流的做法是使用线程池,JDK的线程池:package com.concurrent.warmingUp; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ShowThreadPool { public static void main(String[] args) { // new ShowThreadPool().execInCachedThreadPool(); // new ShowThreadPool().execInFixedThreadPool(); new ShowThreadPool().execInSingleThreadPool(); } private void execInCachedThreadPool() { ExecutorService exec = Executors.newCachedThreadPool(); CommonExecSomeTasks(exec); // 执行完当前任务后停止,不再接受新认为 exec.shutdown(); } private void execInFixedThreadPool() { // 一次完成线程创建,不用每次都创建并加入新的线程 ExecutorService exec = Executors.newFixedThreadPool(5); CommonExecSomeTasks(exec); // 执行完当前任务后停止,不再接受新认为 exec.shutdown(); } private void execInSingleThreadPool() { // 如果对SingleThreadExecutor提交多个任务,那么这些任务将会排队执行。 // SingleThreadExecutor 会序列化所有提交的任务,并维护一个悬挂任务队列 ExecutorService exec = Executors.newSingleThreadExecutor(); CommonExecSomeTasks(exec); exec.shutdown(); } private void CommonExecSomeTasks(ExecutorService exec) { for (int i = 0; i < 5; i++) { exec.execute(new LiftOff()); } } }
join():Waits for this thread to die.
线程A执行了threadB.join()语句,其含义是:线程A等待threadB结束后, 才从threadB.join()中返回Thread.join()
Thread.join(long millis)
Thread.join(long mills,int nanos)
package com.concurrent.warmingUp; class Sleeper extends Thread { private int duration; public Sleeper(String name, int sleepTime) { super(name); duration = sleepTime; start(); } public void run() { try { System.out.println(getName() + "to sleep"); sleep(duration); System.out.println(getName() + " was interrupted. " + "isInterrupted(): " + isInterrupted()); } catch (InterruptedException e) { e.printStackTrace(); System.out.println(getName() + " was interrupted. " + "isInterrupted(): " + isInterrupted()); return; } System.out.println(getName() + " has awakened"); } } class Joiner extends Thread { private Sleeper sleeper; public Joiner(String name, Sleeper sleeper) { super(name); this.sleeper = sleeper; start(); } public void run() { try { System.out.println("Waits for this thread to die,name:" + sleeper.getName()); sleeper.join(); } catch (InterruptedException e) { System.out.println("Interrupted:" + e); } System.out.println(getName() + " join completed"); } } public class Joining { public static void main(String[] args) { Sleeper sleepy = new Sleeper("Sleepy", 1500); // Sleeper grumpy = new Sleeper("Grumpy", 1500); Joiner dopey = new Joiner("Dopey", sleepy); // Joiner doc = new Joiner("Doc", grumpy); dopey.interrupt(); } }
相关文章推荐
- java学习之IO装饰设计模式
- [JavaEE]JaveEE遇到的的问题
- java学习之IO文件分割
- java学习之IO对象流
- java中的String类常量池详解
- java学习之实现文件的复制
- java学习之字符流与字节流的转换
- java学习之IO字符流
- Java学习之IO字节流
- java学习之二叉树的实现
- MyBatis——MyEclipse中使用mybatis-generator
- [Java]泛型方法思路整理
- JavaSE-接口应用举例
- Java学习之链表
- SpringMvc 之自动注解
- java之注解
- Eclipse打包jar文件
- Java学习之IO之File类二
- Freemarker 之 Java静态化 实例一
- Java学习之javassist