2015-12-11 37 views
4

我真的很感謝所有的幫助,但我現在正在努力完成任務的最後部分,這是爲了使增量和減量發生交替。我已編輯,包括我的主類和增量類,其中包含一個for循環,調用Main.increment給定次數(有一個類減法器,它的風格方式與icrementer相同,所以我沒有包括它)。你能幫助我怎麼做到這一點。如果IVE正確認識我期待使1和0之間sharedValue觸發值Java和模擬Process Schedular

public class Main extends Thread { 

private static int sharedValue = 0; 
private static Semaphore semaphore = new Semaphore(1); 

public static void increment() { 
    semaphore.down(); 
    sharedValue++; 
    semaphore.up(); 
} 

public static void decrement() { 
    semaphore.down(); 
    sharedValue--; 
    semaphore.up(); 
} 

static int numberOfCycles = 20000; 

public static void main(String[] args) throws InterruptedException { 

    incrementer inc = new incrementer(numberOfCycles); 
    inc.start(); 
    inc.join(); 

    decrementer dec = new decrementer(numberOfCycles); 
    dec.start(); 
    dec.join(); 

    System.out.println(sharedValue); 

}} 

Semaphore類

private int count; 
// Constructor 
public Semaphore(int n) { 
    count = n; 
} 

// Only the standard up and down operators are allowed. 
public synchronized void down() { 

    while (count == 0) { 

     try { 
      wait(); // Blocking call. 
     } catch (InterruptedException exception) { 
     } 
    } 
    count--; 
} 

public synchronized void up() { 
    count++; 
    notify(); 
    } 
} 

增量器類

公共類增量繼承Thread {

private int numberOfIncrements;

public incrementer(int numOfIncrements){ 
    numberOfIncrements = numOfIncrements; 
} 
public void run(){ 
    for(int i = 0; i <= numberOfIncrements; i++){ 
    Main.increment(); 
} 
} 

}再次

感謝。

+0

在OS書籍中,您可以看到Process Schedular。在所有操作系統書中談到信號量 – shayan

回答

3

我認爲他的意思是受信號量的保護。所以,你會使用類似於:

class ProtectedCount { 
    private static int sharedValue = 0; 
    private static Semaphore semaphore = new Semaphore(1); 
    public void increment() { 
     semaphore.down(); // wait till the semaphore is available 
     sharedValue++; 
     semaphore.up(); // tell everyone that the semaphore is available 
    } 
    // same thing for decrement() 
} 

這表明使用信號量提供互斥。這個用例與互斥體相似。見semaphore vs. mutex on Wikipedia

+0

這真的很有幫助謝謝你,但我的答案有幾個問題。 sharedValue發生了什麼,您的解決方案如何保護它?我也意識到,我忘了在原來的帖子中提問,但是圍繞運營商打電話是什麼意思。 –

0

在Semaphore類中,您可能希望確保「up」方法不會將計數增加到在構造函數中傳遞的「n」之外。

// Constructor 
public Semaphore(int n) { 
    count = n; 
} 

public synchronized void up() { 
    count++; //Ensure count doesn't exceed n. 
    notify(); 
    }