2017-09-16 77 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的公平性设置在这里没有什么帮助。