1 public String[] formart(String[] numbers) { 2 ExecutorService ex = Executors.newFixedThreadPool(3); 3 int size = numbers.length; 4 String[][] pp = new String[size][ size]; 5 for (int i = 0; i < numbers.length; i++) { 6 int k = i; 7 ex.execute(() -> { 8 System.out.println(Thread.currentThread().getName()+" 開始處理--------"); 9 char[] chars = numbers[k].toCharArray(); 10 for (int j = 0; j < chars.length; j++) { 11 pp[ j % size ][k] = String.valueOf(chars[ j ]); 12 } 13 }); 14 } 15 ex.shutdown(); 16 String[] result = new String[size]; 17 for (int i = 0; i <pp.length ; i++) { 18 StringBuffer sb = new StringBuffer(); 19 for (String s : pp[i]) { 20 sb.append(s); 21 } 22 result[i] = sb.toString(); 23 } 24 return result; 25 }
1 public class Demo2 { 2 3 public static volatile int index = 0; 4 public static void main(String[] args) { 5 ThreadTest t1 = new ThreadTest("線程1" , 0); 6 ThreadTest t2 = new ThreadTest("線程2" , 1); 7 ThreadTest t3 = new ThreadTest("線程3" , 2); 8 ThreadTest t4 = new ThreadTest("線程4" , 3); 9 t1.start(); 10 t2.start(); 11 t3.start(); 12 t4.start(); 13 14 } 15 static class ThreadTest extends Thread { 16 private int i; 17 public ThreadTest(String name , int i) { 18 super(name); 19 this.i = i; 20 } 21 @Override 22 public void run() { 23 while ( true ) { 24 if ( (index & 3) == i ) { 25 System.out.println(Thread.currentThread().getName() + ":" + (i+1)); 26 index++; 27 } 28 } 29 } 30 31 } 32 33 }
這兒先貼一個看到的比較好的答案,本身利用AQS實現鎖,讓全部汽車都可以經過這個鎖類來控制通行。引用地址:https://segmentfault.com/q/1010000016621995/a-1020000016628980java
這兒實現了tryAcquireShared方法經過判斷紅綠燈來決定是讓其獲取鎖。這兒注意是實現共享鎖方法因此下面的汽車都可以得到這把鎖segmentfault
1 import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 import java.util.ArrayList; 5 import java.util.Collection; 6 import java.util.List; 7 import java.util.concurrent.locks.AbstractQueuedSynchronizer; 8 9 /** 10 * 交通訊號燈實現 11 * 等紅燈亮時把全部汽車線程都暫停,當綠燈亮時把全部線程都啓動起來 12 * @author ccr at 20181008 13 */ 14 public class TrafficLightLatch { 15 private final class Sync extends AbstractQueuedSynchronizer { 16 @Override 17 protected int tryAcquireShared(int ignored) { 18 return redLight == 0 ? 1 : -1; 19 } 20 21 @Override 22 protected boolean tryReleaseShared(int arg) { 23 return true; 24 } 25 } 26 27 /** 28 * 信號燈狀態,非0表明紅燈,0表明綠燈 29 */ 30 volatile private int redLight; 31 32 private Sync sync; 33 34 /** 35 * 初始化 36 * @param redLight 初始紅綠燈狀態,非0表明紅燈,0表明綠燈 37 */ 38 public TrafficLightLatch(int redLight) { 39 this.redLight = redLight; 40 sync = new Sync(); 41 } 42 43 /** 44 * 紅燈則等待,綠燈則直接經過 45 * @throws InterruptedException 46 */ 47 public void await() throws InterruptedException { 48 sync.acquireSharedInterruptibly(1); 49 } 50 51 /** 52 * 切換爲紅燈 53 */ 54 public void switchRed(){ 55 this.redLight = 1; 56 } 57 58 /** 59 * 切換爲綠燈 60 */ 61 public void switchGreen() { 62 this.redLight = 0; 63 sync.releaseShared(0); 64 } 65 66 /** 67 * 是否有線程等待 68 */ 69 public boolean hasQueuedThreads() { 70 return sync.hasQueuedThreads(); 71 } 72 73 /** 74 * 等待中的線程 75 * @return Collection 76 */ 77 public Collection<Thread> getQueuedThreads() { 78 return sync.getQueuedThreads(); 79 } 80 81 public String getLightColor() { 82 return redLight == 0 ? "綠燈" : "紅燈"; 83 } 84 85 //測試用例 86 public static void main(String[] args) throws IOException, InterruptedException { 87 //初始化交通訊號燈爲紅燈 88 TrafficLightLatch light = new TrafficLightLatch(1); 89 List<Thread> threads = new ArrayList<>(); 90 //10個線程模擬車輛 91 for (int i = 0; i < 10; i++) { 92 Thread thread = new Thread(() -> { 93 while (!Thread.currentThread().isInterrupted()) { 94 //System.out.println(String.format("%s: 信號燈-%s",Thread.currentThread().getName(),light.getLightColor())); 95 try { 96 //綠燈直接通行,紅燈阻塞等待 97 light.await(); 98 } catch (InterruptedException e) { 99 //恢復中斷 100 Thread.currentThread().interrupt(); 101 } 102 try { 103 Thread.sleep(2000); 104 } catch (InterruptedException e) { 105 //恢復中斷 106 Thread.currentThread().interrupt(); 107 } 108 System.out.println(String.format("%s: 信號燈-%s 通行",Thread.currentThread().getName(),light.getLightColor())); 109 } 110 }); 111 threads.add(thread); 112 thread.start(); 113 } 114 115 //等待輸入命令切換交通訊號燈 116 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 117 String command; 118 while ((command = reader.readLine()) != null) { 119 if(command.equals("switchRed")) { 120 light.switchRed(); 121 Thread.sleep(1000); 122 System.out.println(String.format("等待線程數:%d",light.getQueuedThreads().size())); 123 } else if(command.equals("switchGreen")) { 124 light.switchGreen(); 125 Thread.sleep(500); 126 System.out.println(String.format("等待線程數:%d",light.getQueuedThreads().size())); 127 } else if (command.equals("stop")){ 128 System.out.println("terminating..."); 129 threads.forEach(Thread::interrupt); 130 break; 131 } 132 } 133 } 134 }
而後是我本身實現的代碼數組
1 public class Demo4 { 2 3 public static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 4 public static Lock readLock = readWriteLock.readLock(); 5 public static Lock writeLock = readWriteLock.writeLock(); 6 public static void main(String[] args) throws IOException { 7 writeLock.lock(); 8 try { 9 new CartThread("汽車A").start(); 10 new CartThread("汽車B").start(); 11 new CartThread("汽車C").start(); 12 System.out.println("請輸入信號燈 red爲紅燈 green爲綠燈"); 13 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 14 String command; 15 while ((command = reader.readLine()) != null) { 16 if(command.equals("red")) { 17 System.out.println("紅燈亮 全部車中止通行"); 18 if(readWriteLock.getWriteHoldCount()==0) 19 writeLock.lock(); 20 }else if(command.equals("green")){ 21 System.out.println("綠燈亮 全部車開始通行"); 22 writeLock.unlock(); 23 } 24 } 25 }finally { 26 writeLock.unlock(); 27 } 28 } 29 static class CartThread extends Thread{ 30 public CartThread(String name) { 31 super(name); 32 } 33 @Override 34 public void run() { 35 while ( true ){ 36 readLock.lock(); 37 System.out.println(Thread.currentThread().getName()+" :綠燈--發車"); 38 try { 39 Thread.sleep(2000); 40 } catch (InterruptedException e) { 41 }finally { 42 readLock.unlock(); 43 } 44 } 45 } 46 } 47 }