⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 semproc.java

📁 本程序是国外经典的操作系统调度试验
💻 JAVA
字号:
import java.util.Random ;class SemProc extends Thread {    private SemScheduler mySched ;     private int count ;    private static Random threadSeed = new Random() ;    private static int noProcs = 0 ;    private static int barCounter = 0 ;    private static Semaphore mutex = new Semaphore(1) ;    private static Semaphore barQueue = new Semaphore(0) ;    private static long getSeed() {        return 1 + threadSeed.nextLong() ;    }    public SemProc(SemScheduler sch, String name, int i) {	super(name) ;	mySched = sch ;	noProcs++ ;	count = i ;        start() ;    }    private int collatz(int i) {	int ans = 0 ;	while (i != 1) {		if (i <= 0) return -1 ; // numbers get too big!		ans++ ;		if (i % 2 == 0) i /= 2 ;		else i = i*3 + 1 ;	}	return ans ;    }    private void reachBarrier(boolean lastTime) {        mutex.wait(this) ;        barCounter++ ;        if (barCounter == noProcs) {		if (lastTime) noProcs-- ;		if (barCounter > 1) barQueue.signal() ;		else { 		    barCounter = 0 ; 		    mutex.signal() ;		}	} else {            mutex.signal() ; // must let others in and wait            barQueue.wait(this) ;            barCounter -- ;	    if (lastTime) noProcs-- ;            if (barCounter > 1)  // i.e. more waiters                barQueue.signal() ;             else {        // the last waiter                barCounter = 0 ; // reset barrier                mutex.signal() ;            }        }    }    public void addToReadyQueue(boolean starting) {	mySched.addProcess(this, starting) ;    }    public void removeFromReadyQueue() {	mySched.removeProcess(this) ;    }    public void run() {	addToReadyQueue(true) ;	Random myrand = new Random(getSeed()) ;	while(count > 0) {		int k = Math.abs(myrand.nextInt()) ;		int ans = collatz(k) ;		if (ans > 0) count-- ;		System.out.println("This is " + getName() + " - Collatz of "			+ k + " is " + ans) ;                reachBarrier(count==0) ;	}	removeFromReadyQueue() ;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -