从三个线程 排队打印 , 到 多个线程打印
第一中 大暴力
直接 while 循环 判断mark
private static class Two implements Runnable { static volatile int mark = 0; static int N = 10; static ThreadPoolExecutor executor = new ThreadPoolExecutor(N, N, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); int idx; public Two(int idx) { this.idx = idx; } @Override public void run() { while (true) { if ((mark - idx) % N == 0) { System.out.println(idx); mark++; } } } static void start() { Two[] threads = new Two[N]; for(int i = 0 ; i < N; i++) { threads[i] = new Two(i); } for(int i = 0 ; i < N ; i++) { executor.submit(threads[i]); } } }
第二种 利用 reentrantLock 的 同步
private static class Three implements Runnable { static int N = 10; static ThreadPoolExecutor executor = new ThreadPoolExecutor(N, N, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>()); static Lock lock = new ReentrantLock(); static Condition[] conditions = new Condition[N]; static { for (int i = 0 ; i < N ; ++i) { conditions[i] = lock.newCondition(); } } int idx; Condition pre; Condition next; public Three(int idx) { this.idx = idx; pre = conditions[ (idx + N - 1)%N]; next = conditions[idx]; } @Override public void run() { lock.lock(); try { while (true) { pre.await(); System.out.println(idx); next.signal(); } } catch (Exception e) { e.printStackTrace(); } finally { lock.unlock(); } } static void start() { Three[] threads = new Three[N]; for(int i = 0 ; i < N; i++) { threads[i] = new Three(i); } for(int i = 0 ; i < N ; i++) { executor.submit(threads[i]); } lock.lock(); try { conditions[N - 1].signal(); } finally { lock.unlock(); } } }
第三种 利用 sychronized 和 reentrantLock 同理
private static class One implements Runnable {
static int N = 10;
static ThreadPoolExecutor executor = new ThreadPoolExecutor(N, N, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
private Object pre;
private Object next;
private String name;
public One(String name) {
this.pre = pre;
this.next = next;
this.name = name;
}
@Override
public void run() {
synchronized (pre) {
while (true) {
try {
pre.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name);
synchronized (next) {
next.notify();
}
}
}
}
static void start() {
One[] threads = new One[N];
for(int i = 0 ; i < N; i++) {
threads[i] = new One(i+"");
}
for(int i = 0 ; i < N; i++) {
threads[i].next = threads[i];
threads[i].pre = threads[(i + N - 1) % N];
}
for(int i = 0 ; i < N ; i++) {
executor.submit(threads[i]);
}
// 由于用的 现成的 monitor 所以千万不要调用现成的 一些 synchronized 方法,最好 自定义 一些Object,这里图省事了
synchronized (threads[N-1]) {
threads[N - 1].notify();
}
}
}