?????????
?????????????????????PV?????????????????0?????acquire()??????????????????????????release()????????????????????ж??
1???? /**
2      * Semaphore
3      */
4     public void semaphore() {
5         Semaphore sem = new Semaphore(1);
6         int nThread = 5;
7         for (int i = 0; i < nThread; i++) {
8             Thread t = new Thread() {
9                 public void run() {
10                     try {
11                         sem.acquire();
12                         int random = (int) (5 * Math.random());
13                         sleep(random);
14                         System.out.println(currentThread().getId());
15                         sem.release();
16                     } catch (InterruptedException e) {
17                         e.printStackTrace();
18                     }
19                 }
20             };
21             t.start();
22         }
23     }
???????
???????????????????????await()????????????????????????????????ж??????????????????????????????????????????л????????????ι???
1 ????/**
2      * ???
3      * @return
4      * @throws InterruptedException
5      */
6     public long cyclicBarrier() throws InterruptedException {
7         int nThreads = 25;
8         final CyclicBarrier barrier = new CyclicBarrier(5?? new Runnable() {
9             @Override
10             public void run() {
11                 System.out.println("Barrier pass...");
12             }
13         });
14
15         for (int i = 0; i < nThreads; i++) {
16             Thread t = new Thread() {
17                 public void run() {
18                     try {
19                         barrier.await();
20                         sleep(1000);
21                     } catch (BrokenBarrierException | InterruptedException e) {
22                         e.printStackTrace();
23                     }
24                 }
25             };
26             t.start();
27         }
28     }
??????????????????
????CompletionService
???????Executor?????????????????ж?????????????????н?????д????????ExecutorService???????????????????ο?JDK?????
1 ????/**
2      * CompletionService
3      */
4     public void completionService() {
5         int nThread = 5;
6         ExecutorService executor = Executors.newFixedThreadPool(5);
7         CompletionService  completionService = new ExecutorCompletionService(executor);
8
9         for (int i = 0; i < nThread; i++) {
10             completionService.submit(new Callable<String>() {
11                 @Override
12                 public String call() throws Exception {
13                     if (Thread.currentThread().isInterrupted()) {
14                         return "interrupted";
15                     }
16                     int st = (int)(Math.random() * 5000);
17                     Thread.sleep(st);
18                     return Thread.currentThread().getId() + ":" + st;
19                 }
20             });
21         }
22
23         for (int i = 0; i < nThread; i++) {
24             try {
25                 Future<String> f = completionService.take();
26                 System.out.println("Round" + i);
27                 System.out.println(f.get());
28             } catch (InterruptedException | ExecutionException e) {
29                 e.printStackTrace();
30             }
31
32         }
33     }
?????趨???????????
??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ?????????????????????????
1 ????/**
2      * ???: ???????????ж?????е?????????????????????????????????????timedRun????????join??????
3      * ??join???????????????????????е????????????????Throwable???????????乲????????????volatile
4      */
5     public void timeRun(final Runnable r) throws Throwable {
6         ScheduledExecutorService cancelExec = Executors.newScheduledThreadPool(5);
7         class  RethrowableTask implements Runnable {
8             private volatile Throwable t;
9             @Override
10             public void run() {
11                 try {
12                     r.run();
13                 } catch (Throwable t) {
14                     this.t = t;
15                 }
16             }
17             void rethrow() throws Throwable {
18                 if (t != null) {
19                     throw t;
20                 }
21             }
22         }
23
24         RethrowableTask task = new RethrowableTask();
25         final Thread taskThread = new Thread(task);
26         taskThread.start();
27         cancelExec.schedule(() -> taskThread.interrupt()?? 100000?? TimeUnit.MILLISECONDS);
28         taskThread.join(10000);
29         task.rethrow();
30     }
?????????????Future??????get()???????????????????????????£?????????????????????
????1 ????public void betterTimeRun(Runnable r) throws Throwable {
????2         ExecutorService executorService = Executors.newFixedThreadPool(5);
????3         Future<?> task = executorService.submit(r);
????4         try {
????5             task.get(10000?? TimeUnit.MILLISECONDS);
????6         } catch (TimeoutException e) {
????7             // ??finally?б????
????8         } catch (ExecutionException e) {
????9             throw e.getCause();
????10         } finally {
????11             task.cancel(true);
????12         }
????13     }
??????try…catch…finally?????????
????UncaughtExcption?????
????Thread??run???????????????????????????try…catch???????????????????Щ?????????????б?????
??????????????????Thread?????????setUncaughtExceptionHandler???κ?????????????? UncaughtExceptionHandler?????????????Thread?????????setUncaughtExceptionHandler? ???????????????UncaughtExceptionHandler?????????????
????1 class MyHandler implements Thread.UncaughtExceptionHandler {
????2         /**
????3          * ????unchecked???????????UncaughtExceptionHandler????????????????δ??????????????JVM??????????汨????ó???????
????4          * UncaughtExceptionHandler???????????κ????????????????????????????????????System.error
????5          */
????6         @Override
????7         public void uncaughtException(Thread t?? Throwable e) {
????8             // Do something...
????9         }
????10     }
???????????????????Handler?????JVM????????????????????System.error??
???????汻?????????
???????????????????????汻???????????????????AbstractExcecutorService????????????????м????????′μ????????
1 ????/**
2      * ?????????????汻?????????
3      */
4     class TrackingExecutor extends AbstractExecutorService {
5         private final ExecutorService exec;
6         private final Set<Runnable> tasksCancelledAtShutdown = Collections.synchronizedSet(new HashSet<Runnable>());
7
8         public TrackingExecutor() {
9             this.exec = Executors.newCachedThreadPool();
10         }
11
12         public List<Runnable> getCancelledTasks() {
13             if (!exec.isTerminated()) {
14                 throw new IllegalStateException("...");
15             }
16             return new ArrayList<Runnable>(tasksCancelledAtShutdown);
17         }
18
19         @Override
20         public void execute(Runnable command) {
21             exec.execute(new Runnable() {
22                 @Override
23                 public void run() {
24                     try {
25                         command.run();
26                     } finally {
27                         if (isShutdown() && Thread.currentThread().isInterrupted()) {
28                             tasksCancelledAtShutdown.add(command);
29                         }
30                     }
31                 }
32             });
33         }
34     }
????????????????????????????汻??????????????run??????try???Χ?У?????????ж???????????????????????? taskCancelledAtShutdown?У???????????д??exceute????????????????????и?ExecutorService??