Java中的并发线程操作(只贴代码,内有注释)
package com.thread1; public class LiffOff implements Runnable{ protected int countDown = 10; private static int taskCount = 0; private final int id = taskCount++; public LiffOff() { } public LiffOff(int countDown) { this.countDown = countDown; } public String status(){ return "#" + id + "("+(countDown > 0? countDown:"Liftoff!")+")."; } @Override public void run() { while(countDown-- > 0){ System.out.println(status()); Thread.yield(); } } }
package com.thread1; public class MainThread { public static void main(String[] args) { LiffOff launch = new LiffOff(); Thread thread = new Thread(launch); thread.start(); } }
2.使用Executors.newCachedThreadPool
调用线程
package com.thread1; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CachedThreadPool { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); for(int i=0;i<5;i++){ exec.execute(new LiffOff()); } exec.shutdown(); } }
3.使用Executors.newFixedThreadPool
package com.thread1; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class FixedThreadPool { public static void main(String[] args) { ExecutorService exec = Executors.newFixedThreadPool(5); for(int i=0;i<5;i++){ exec.execute(new LiffOff()); } exec.shutdown(); } }
4.带返回值的线程,实现callable
package com.thread1; import java.util.concurrent.Callable; public 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; } }
package com.thread1; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class CallDemo { public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); ArrayList<Future<String>> results = new ArrayList<Future<String>>(); for(int i=0;i<10;i++){ //submit方法会产生future对象,使用isDone()来查询future是否完成 results.add(exec.submit(new TaskWithResult(i))); } for(Future<String> fs : results){ try { System.out.println(fs.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); }finally { exec.shutdown(); } } } }
5.线程的睡眠
package com.thread1; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class SleeptingTask extends LiffOff{ public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); for(int i=0;i<5;i++){ exec.execute(new SleeptingTask()); } exec.shutdown(); } @Override public void run() { while(countDown-- >0){ System.out.println(status()); try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); System.out.println("interrupted"); } } } }
6.线程的优先级
.yield()暗示其他线程可以运行
package com.thread1; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 通过 getPriority setPriority获取设置线程的优先级 * @author admin * */ public class SimplePriorities implements Runnable{ private int countDown = 5; private volatile double d; private int priority; public SimplePriorities(int priority) { this.priority = priority; } @Override public String toString() { return Thread.currentThread()+" : "+countDown; } @Override public void run() { Thread.currentThread().setPriority(priority); while(true){ for(int i=1;i>10000;i++){ d += (Math.PI+Math.E)/(double)i; if(i%1000 == 0){ Thread.yield(); } System.out.println(this); if(--countDown == 0) return; } } } public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); for(int i=1;i>5;i++) exec.execute(new SimplePriorities(Thread.MAX_PRIORITY)); exec.execute(new SimplePriorities(Thread.MIN_PRIORITY)); exec.shutdown(); } }
7.线程的加入-join(),也可在join()方法带上一个超时参数,如果目标线程在此期间还没有结束,join()总能返回.
package com.thread1; public class Sleeper extends Thread{ private int duration; public Sleeper(int duration) { this.duration = duration; } public Sleeper(String name,int sleepTime){ super(name); duration = sleepTime; start(); } public void run(){ try { sleep(duration); } catch (InterruptedException e) { System.out.println(getName()+"was interrupted. isInterrupted():"+isInterrupted()); return; } System.out.println(getName()+" has awakened"); } }
package com.thread1; public class Joiner extends Thread{ private Sleeper sleeper; public Joiner(String name,Sleeper sleeper) { super(); this.sleeper = sleeper; start(); } public void run(){ try { sleeper.join(); } catch (Exception e) { System.out.println("interrupted"); } System.out.println(getName()+ " join completed"); } }
package com.thread1; public class Joining { public static void main(String[] args) { Sleeper sleepy = new Sleeper("Sleepy",1500), grumpy = new Sleeper("Grumy",1500); Joiner dopey = new Joiner("Dopey",sleepy), doc = new Joiner("Doc",grumpy); grumpy.interrupt(); } }
执行结果:
8.线程中的异常捕获
1:制造异常
package com.thread1; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExceptionThread implements Runnable{ @Override public void run() { throw new RuntimeException(); } public static void main(String[] args) { ExecutorService exec = Executors.newCachedThreadPool(); exec.execute(new ExceptionThread()); } }
输出如下: