2014-09-24 48 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. 當一個線程進入同步的塊,這將接管監視器上的鎖。如果其收件人