2017-09-16 69 views
0

我想了解信號量的公平性設置(int num,boolean how)。 我有這個程序。公平性設置似乎不起作用。信號量公平設置

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


     shared sh=new shared(); 
     Semaphore sm=new Semaphore(1,true); 
     newthread1 nh1=new newthread1(sm,sh,"nh1"); 

     newthread1 nh3=new newthread1(sm, sh,"nh3"); 
     newthread1 nh2=new newthread1(sm, sh,"nh2"); 
     } 
} 



Class shared:- 

public class shared { 

    public void msg() 
    { 
     for(int i=65;i<68;i++) { 
      System.out.println(Thread.currentThread().getName()+ " " + (char)i); 

     } 
    } 

} 

    class new thread:- 
import java.util.concurrent.*; 
public class newthread1 implements Runnable { 
    shared sh=null; 
    Semaphore sem=null; 
    Thread t=null; 
    String name=null; 
    public newthread1(Semaphore sem,shared sh,String name) { 
     // TODO Auto-generated constructor stub 
     this.sem=sem; 
     this.sh=sh; 
     this.name=name; 

     t=new Thread(this,name); 
     t.start(); 
    } 

    @Override 
    public void run() { 

     try { 
      sem.acquire(); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

     System.out.println(Thread.currentThread().getName() +" has accuqired the lock"); 
     sh.msg(); 

     sem.release(); 
     // TODO Auto-generated method stub 

    } 
    } 

在這裏糾正我的理解: - 我的理解是等待線程應該獲得鎖,他們已要求lock.if我運行它,它不給我正確的結果的順序。 每次給出不同的結果。

謝謝你

+0

一個觀察是,你不能真正知道他們要求鎖的順序。你不知道這些線程按照你啓動它們的確切順序調用了「acquire」方法。 – rhobincu

回答

0

你可能會認爲你開始線程的順序很重要。它不是。重要的是哪個線程首先到達sem.acquire()

Semaphore的公平性設置在這裏沒有什麼幫助。