标签:锁定 print future repo splay priority middle std 命令
1 /** 2 * 代码演示线程死锁 一个简单的死锁类 3 * 4 * 当DeadLock类的对象flag==1时(lock1),先锁定o1,睡眠500毫秒 5 * 6 * 而lock1在睡眠的时候另一个flag==0的对象(lock2)线程启动,先锁定o2,睡眠500毫秒 7 * 8 * lock1睡眠结束后需要锁定o2才能继续执行,而此时o2已被lock2锁定; 9 * 10 * lock2睡眠结束后需要锁定o1才能继续执行,而此时o1已被lock1锁定; 11 * 12 * lock1、lock2相互等待,都需要得到对方锁定的资源才能继续执行,从而死锁。 13 */ 14 15 public class TestDeadLock implements Runnable { 16 public int flag = 1; 17 static Object o1 = new Object(), o2 = new Object(); 18 19 @Override 20 public void run() { 21 System.out.println("flag=" + flag); 22 if (flag == 1) { 23 synchronized (o1) { 24 try { 25 Thread.sleep(1000); 26 } catch (InterruptedException e) { 27 // TODO Auto-generated catch block 28 e.printStackTrace(); 29 } 30 synchronized (o2) { 31 System.out.println("1"); 32 } 33 } 34 } 35 if (flag == 0) { 36 synchronized (o2) { 37 try { 38 Thread.sleep(500); 39 } catch (InterruptedException e) { 40 // TODO Auto-generated catch block 41 e.printStackTrace(); 42 } 43 synchronized (o1) { 44 System.out.println("0"); 45 } 46 } 47 } 48 } 49 50 public static void main(String[] args) throws InterruptedException { 51 TestDeadLock lock1 = new TestDeadLock(); 52 TestDeadLock lock2 = new TestDeadLock(); 53 54 lock1.flag = 1; 55 lock2.flag = 0; 56 57 new Thread(lock1).start(); 58 new Thread(lock2).start(); 59 } 60 61 }
9.与多线程相关的几个API
threadLocal :是每个线程独立拥有的对象,在当前线程中数据共享。set() 、get()方法====Map<Thread,变量>
timer: 定时器 请见timertest。new Timer().schedule(new TimerTask(){});创建一个定时器->计划什么时候执行->创建一个任务放到计划里
CountDownLatch:一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。await()->countDown()->当计数器为0时,程序才继续向下执行(很有用。)
1 package tcl.o2o.it.threadinjdk5; 2 3 import java.util.concurrent.CountDownLatch; 4 import java.util.concurrent.ExecutorService; 5 import java.util.concurrent.Executors; 6 7 public class Learn03CountdownLatchTest { 8 9 public static void main(String[] args) { 10 ExecutorService service = Executors.newCachedThreadPool(); // 创建一个线程池 11 final CountDownLatch cdOrder = new CountDownLatch(1);// 指挥官的命令,设置为1,指挥官一下达命令,则cutDown,变为0,战士们执行任务 12 final CountDownLatch cdAnswer = new CountDownLatch(3);// 因为有三个战士,所以初始值为3,每一个战士执行任务完毕则cutDown一次,当三个都执行完毕,变为0,则指挥官停止等待。 13 for (int i = 0; i < 3; i++) { 14 Runnable runnable = new Runnable() { 15 public void run() { 16 try { 17 System.out.println("线程" + Thread.currentThread().getName() + "正准备接受命令"); 18 cdOrder.await(); // 战士们都处于等待命令状态 19 System.out.println("线程" + Thread.currentThread().getName() + "已接受命令"); 20 Thread.sleep((long) (Math.random() * 10000)); 21 System.out.println("线程" + Thread.currentThread().getName() + "回应命令处理结果"); 22 cdAnswer.countDown(); // 任务执行完毕,返回给指挥官,cdAnswer减1。 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } 26 } 27 }; 28 service.execute(runnable);// 为线程池添加任务 29 } 30 try { 31 Thread.sleep((long) (Math.random() * 10000)); 32 33 System.out.println("线程" + Thread.currentThread().getName() + "即将发布命令"); 34 cdOrder.countDown(); // 发送命令,cdOrder减1,处于等待的战士们停止等待转去执行任务。 35 System.out.println("线程" + Thread.currentThread().getName() + "已发送命令,正在等待结果"); 36 cdAnswer.await(); // 命令发送后指挥官处于等待状态,一旦cdAnswer为0时停止等待继续往下执行 37 System.out.println("线程" + Thread.currentThread().getName() + "已收到所有响应结果"); 38 } catch (Exception e) { 39 e.printStackTrace(); 40 } 41 service.shutdown(); // 任务结束,停止线程池的所有线程 42 43 } 44 }
10.Lock 和 Condition
1 package tcl.o2o.it.threadinjdk5; 2 3 import java.util.concurrent.Callable; 4 import java.util.concurrent.ExecutionException; 5 import java.util.concurrent.ExecutorService; 6 import java.util.concurrent.Executors; 7 import java.util.concurrent.Future; 8 9 public class Learn06ThreadFutureAndCallable01 { 10 11 public static void main(String[] args) throws InterruptedException, ExecutionException { 12 // TODO Auto-generated method stub 13 ExecutorService es = Executors.newSingleThreadExecutor(); 14 Future<String> future = es.submit(new Callable<String>() { 15 @Override 16 public String call() throws Exception { 17 // TODO Auto-generated method stub 18 System.out.println("线程开始执行"); 19 Thread.sleep(1000); 20 return "hello world"; 21 } 22 }); 23 24 es.shutdown(); 25 System.out.println("等待返回结果"); 26 System.out.println(future.get()); 27 } 28 29 }
14.Semaphore-信号灯机制 当我们创建一个可扩展大小的线程池,并且需要在线程池内同时让有限数目的线程并发运行时,就需要用到Semaphore(信号灯机制)。acquire和release方法。
1 public class Learn08SemaphoreTest { 2 public static void main(String[] args) { 3 ExecutorService service = Executors.newCachedThreadPool(); 4 final Semaphore sp = new Semaphore(3); 5 for (int i = 0; i < 5; i++) { 6 Runnable runnable = new Runnable() { 7 public void run() { 8 try { 9 sp.acquire(); 10 } catch (InterruptedException e1) { 11 e1.printStackTrace(); 12 } 13 System.out.println("线程" + Thread.currentThread().getName() + "进入,当前已有" 14 + (3 - sp.availablePermits()) + "个并发"); 15 try { 16 Thread.sleep((long) (Math.random() * 10000)); 17 } catch (InterruptedException e) { 18 e.printStackTrace(); 19 } 20 System.out.println("线程" + Thread.currentThread().getName() + "即将离开"); 21 sp.release(); 22 // 下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元 23 System.out.println("线程" + Thread.currentThread().getName() + "已离开,当前已有" 24 + (3 - sp.availablePermits()) + "个并发"); 25 } 26 }; 27 service.execute(runnable); 28 } 29 } 30 }
1 package tcl.o2o.it.threadinjdk5; 2 3 import java.util.concurrent.ExecutionException; 4 import java.util.concurrent.ForkJoinPool; 5 import java.util.concurrent.Future; 6 import java.util.concurrent.RecursiveTask; 7 8 public class Learn09ForkJoinTest extends RecursiveTask { 9 private static int ThreadShold = 2; 10 int start; 11 int end; 12 13 private Learn09ForkJoinTest(int start, int end) { 14 this.start = start; 15 this.end = end; 16 } 17 18 @Override 19 protected Integer compute() { 20 int sum = 0; 21 boolean flag = (end - start) <= ThreadShold; 22 if (flag) { 23 for (int i = start; i <= end; i++) { 24 sum += i; 25 } 26 } else { 27 int middle = (start + end) / 2; 28 Learn09ForkJoinTest leftTask = new Learn09ForkJoinTest(start, middle); 29 Learn09ForkJoinTest rightTask = new Learn09ForkJoinTest(middle+1, end); 30 31 leftTask.fork();//把任务放到该任务的顶部 32 rightTask.fork(); 33 34 int leftResult = (Integer) leftTask.join();//执行完再往下走 35 int rightResult = (Integer) rightTask.join(); 36 37 sum = leftResult + rightResult; 38 } 39 return sum; 40 } 41 public static void main(String[] args) { 42 ForkJoinPool forkJoinPool = new ForkJoinPool(); 43 long beginTime = System.currentTimeMillis(); 44 Learn09ForkJoinTest task = new Learn09ForkJoinTest(1, 100000); 45 Future<Integer> result = forkJoinPool.submit(task); 46 try { 47 System.out.println(result.get()); 48 System.out.println( System.currentTimeMillis() - beginTime); 49 } catch (InterruptedException e) { 50 // TODO Auto-generated catch block 51 e.printStackTrace(); 52 } catch (ExecutionException e) { 53 // TODO Auto-generated catch block 54 e.printStackTrace(); 55 } 56 57 } 58 }
标签:锁定 print future repo splay priority middle std 命令
原文地址:http://www.cnblogs.com/vvning/p/7516605.html