我对java多线程进行了一个测试,编写了一下代码,但产生的结果我个人却很难解释,代码如下:
Semaphore.java
class Semaphore { private int count; public Semaphore(int n) { this.count = n; } public synchronized void acquire() { while (count == 0) { try { System.out.println(Thread.currentThread().getName()+"我来了。"); wait(); System.out.println(Thread.currentThread().getName()+"我醒了。"); } catch (InterruptedException e) { // keep trying System.err.println(e); } } count--; } public synchronized void release() { count++; notify(); // alert a thread that's blocking on this semaphore } }
public class TestMain { public void semaphoreTest() throws Exception { Semaphore se = new Semaphore(0); class Producer extends Thread { private Semaphore se = null; public Semaphore getSe() { return se; } public void setSe(Semaphore se) { this.se = se; } public void run() { for (int y =0 ; y <10;y++) { try { Thread.sleep(1000L); } catch (Exception e) { System.out.println(e); } System.out.println(this.getName() + ":又产生了三个资源。"); se.release(); se.release(); se.release(); } } } class Consumer extends Thread { private Semaphore se = null; public Semaphore getSe() { return se; } public void setSe(Semaphore se) { this.se = se; } public void run() { while (true) { se.acquire(); System.out.println(this.getName() + ":我获取到资源了。"); } } } Producer pd = new Producer(); pd.setName("Productor"); pd.setSe(se); for (int x = 0; x < 1; x++) { Consumer cs = new Consumer(); cs.setSe(se); cs.setName(String.valueOf(x)); cs.start(); } pd.start(); } public static void main(String[] args) throws Exception { // TODO 自动生成方法存根 TestMain tm = new TestMain(); tm.semaphoreTest(); } }
产生的结果:
0我来了。 Productor:又产生了三个资源。 0我醒了。 0:我获取到资源了。 0我来了。 0我醒了。 0:我获取到资源了。 0:我获取到资源了。 0我来了。 Productor:又产生了三个资源。 0我醒了。
我醒了和我获取到了资源数目不一致,我只有一个thread却似乎有多个thread在运行,对于这个结果不知有哪位可以给以解惑。