引发异常的简单饥饿程序

时间:2014-02-12 14:22:35

标签: java multithreading

我写了三个饥饿计划,但没有一个抛出异常:

"Thread-2" prio=1 tid=0x080db6c8 nid=0x22de waiting for monitor entry [0xa81e4000..0xa81e4150]
      at yourClass.run(yourcCass.java:55)
      - waiting to lock <0xa89fc7f0> (a java.lang.Object)
      - locked <0xa89fcdb0> (a starvation)
      at java.lang.Thread.run(Thread.java:595)

"Thread-1" prio=1 tid=0x080da780 nid=0x22dd waiting for monitor entry [0xa8264000..0xa82650d0]
      at yourClass.run(yourClass.java:55)
      - waiting to lock <0xa89fc7f0> (a java.lang.Object)
      - locked <0xa89fcc48> (a starvation)
      at java.lang.Thread.run(Thread.java:595)

"Thread-0" prio=1 tid=0x080d9100 nid=0x22db in Object.wait() [0xa8366000..0xa8366fd0]
      at java.lang.Object.wait(Native Method)
      - waiting on <0xa89fc978> (a starvation)
      at starvation.run(yourClass.java:62)
      - locked <0xa89fc7f0> (a java.lang.Object)
      - locked <0xa89fc978> (a starvation)
      at java.lang.Thread.run(Thread.java:595)

显示您的程序处于饥饿状态。

任何人都可以帮助处理异常的简单Starvation程序。

提供帮助我写的代码是:

public class ThreadStarvation implements Runnable{

boolean t1Entered = false;

public synchronized void synchronizedTimerMethod(){
    System.out.println(Thread.currentThread().getName()+" enters synchronized block");
    while (!t1Entered && !Thread.currentThread().getName().equals("t1")) { 
        try {
            wait();

        } catch (Exception e) {

        }
    }

    t1Entered = true;

    while (true) {
        try{
            Thread.sleep(5000);
            }
            catch (InterruptedException ie) {}
        System.out.println(Thread.currentThread().getName()+" in synchronized block");

    }
}

public void run(){
    synchronizedTimerMethod();
}

public static void main(String[] args) {
    ThreadStarvation ts1=new ThreadStarvation();

    Thread t1=new Thread(ts1);
    t1.setName("t1");

    Thread t2=new Thread(ts1);
    t2.setName("t2");

    t2.start();

    try{
    Thread.sleep(2000);
    }
    catch (InterruptedException ie) {}

    t1.start();

    try{
        Thread.sleep(16000);
        }
        catch (InterruptedException ie) {}
    System.out.println(t1.getState());
    System.out.println(t2.getState());

  }
}

t2将处于饥饿状态,那么为什么JVM没有给出t2处于饥饿或等待监视器输入的消息?我允许我的程序运行20分钟。

1 个答案:

答案 0 :(得分:0)

jvm不会为饥饿本身抛出异常。线程将继续等待监视器。

如果线程在几次重试后无法获得锁定,则可以使用lock.trylocak并抛出异常。