2014-09-24 51 views
2

我需要一些线程在某检查站同步,只有经过所有线程都达到了这一点,他们应该继续。有没有简单的构造?爪哇 - Synchonize线程在某一点

Integer threadCount = 10; 

for (int i = 0; i < threadCount; i++) 
{ 
    new Thread(() -> 
    { 
     try 
     { 
      doFirst(); 
      synchronized (threadCount) 
      { 
       threadCount--; 
       while (threadCount > 0) 
        threadCount.wait(); 
       threadCount.notifyAll(); 
      } 
      doSecond(); 
     } 
     catch (Exception e) { e.printStackTrace(); } 
    }).start(); 
} 

// all threads are started, to wait until they've finished, call threadCount.wait(); 
+4

退房的CyclicBarrier,CountDownLatch和死锁存在锁定notifyAll的()只能调用。 – user802421 2014-09-24 16:34:24

+0

接下来,'try {...} finally {latch.countDown(); ''是你的朋友。 – 2014-09-24 16:57:11

回答

0

如果:

for (int v = 0; v < 10; v++) { 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 

       doFirst(); 

       //checkpoint 

       doSecond(); 

      } catch (Throwable e) { 
        e.printStackTrace(); 
      } 
     } 
    }).start(); 
} 
+0

似乎是最短的解决方案,我想试试 – wutzebaer 2014-09-24 16:52:49

0

可以使用的锁定对象执行此您知道您可以使用来自java.util.concurrent的CountDownLatch的确切线程数。

// First initialize latch with your number of threads 
CountDownLatch latch = new CountDownLatch(N); 

// Then give this instance of latch to each of your threads 

// and finally at your checkpoint do 
latch.countDown(); 
latch.await(); 

就这样。

+0

这就是java.util.concurrent.CountDownLatch的作用。 – 2014-09-24 16:42:58

+0

@jameslarge不知道这样一类存在,但极大地知道,甲骨文提出了同样的事情:) – msrd0 2014-09-24 16:44:19

2
import java.util.concurrent.CountDownLatch; 
private CountDownLatch countDownLatch = new CountDownLatch(10) 
... 
public void run() { 
    doFirst(); 
    countDownLatch.countDown(); 
    countDownLatch.await(); 
    doSecond(); 
} 

---- OR(1条以下的代码线)----

import java.util.concurrent.CyclicBarrier; 
private CyclicBarrier cyclicBarrier= new CyclicBarrier(10) 
... 
public void run() { 
    doFirst(); 
    cyclicBarrier.await(); 
    doSecond(); 
} 
0

一种方式来做到这一点是你的线程在一个共同的显示器同步:

Object monitor = new Object(); 
int jobCount = 0; 

public void f1(){ 
for (int v = 0; v < 10; v++) { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       try { 

       doFirst(); 
       check();  

       doSecond(); 

       } catch (Throwable e) { 
        e.printStackTrace(); 
       } 
      } 
     }).start(); 
    } 
} 

public void sleep(){} 

public void check(){ 
    synchronized(monitor){ 
     jobCount++; 
     if(jobCount==10){ 
      monitor.notifyAll(); 
      return; 
     } 
    } 
    monitor.wait(); 
} 

需要考虑的事情:

  1. 当你调用monitor.wait(),线程,其中该调用有人将转入休眠状态,在监视器同步
  2. notifyAll的()将唤醒那沉睡和同步所有线程。超过其收件人。
  3. 当一个线程进入同步的块,这将接管监视器上的锁。如果其收件人