在iteye上看到的一道多線程的題目,參考了一下網友的實現,那Eclipse調試經過,算是對JAVA5的併發庫有個大體的瞭解,分享出來,歡迎拍磚。html
題目:java
要求用三個線程,按順序打印1,2,3,4,5.... 71,72,73,74, 75.多線程
線程1先打印1,2,3,4,5, 而後是線程2打印6,7,8,9,10, 而後是線程3打印11,12,13,14,15. 接着再由線程1打印16,17,18,19,20....以此類推, 直到線程3打印到75。併發
分析:感受出題人是要考察一下你是否可以很好的控制多線程,讓他們有序的進行。ide
一、線程池:3個線程,須要使用併發庫的線程池post
二、鎖(lcok):在打印的時候,只容許一個線程進入,其餘的線程等待spa
下面的主要的代碼:.net
- import java.util.HashMap;
- import java.util.Map;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
-
- public class NumberPrinter {
-
- private Lock lock = new ReentrantLock();
-
- private Condition c1 = lock.newCondition();
- private Condition c2 = lock.newCondition();
- private Condition c3 = lock.newCondition();
-
- private Map<Integer, Condition> condtionContext =
- new HashMap<Integer, Condition>();
-
- public NumberPrinter() {
- condtionContext.put(Integer.valueOf(0), c1);
- condtionContext.put(Integer.valueOf(1), c2);
- condtionContext.put(Integer.valueOf(2), c3);
- }
-
- private int count = 0;
-
- public void print(int id) {
- lock.lock();
- try {
- while(count*5 < 75) {
- int curID = calcID();
- if (id == curID) {
- for (int i = 1; i<=5; i++) {
- System.out.print(count*5 +i+ ",");
- }
- System.out.println();
- count++;
- int nextID = calcID();
- Condition nextCondition = condtionContext.get(
- Integer.valueOf(nextID));
-
- nextCondition.signal();
- } else {
- Condition condition = condtionContext.get(
- Integer.valueOf(id));
- condition.await();
- }
- }
-
- for(Condition c : condtionContext.values()) {
- c.signal();
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- lock.unlock();
- }
- }
-
-
- private int calcID() {
-
- return count % 3;
- }
-
-
-
- public static void main(String[] args) {
- ExecutorService executor = Executors.newFixedThreadPool(3);
- final CountDownLatch latch = new CountDownLatch(1);
- final NumberPrinter printer = new NumberPrinter();
- for (int i = 0; i < 3; i++) {
- final int id = i;
- executor.submit(new Runnable() {
- @Override
- public void run() {
-
- try {
- latch.await();
- } catch (InterruptedException e) {
-
- e.printStackTrace();
- }
-
- printer.print(id);
- }
-
- });
- }
-
- System.out.println("三個任務開始順序打印數字。。。。。。");
- latch.countDown();
- executor.shutdown();
- }
-
- }