0

我有以下 3 个线程:

// These are the two resource objects we'll try to get locks for
final Object resource1 = "resource1";
final Object resource2 = "resource2";
final Object resource3 = "resource3";
// Here's the first thread.  It tries to lock resource1 then resource2
Thread t1 = new Thread() {
  public void run() {

    // Lock resource 1
    synchronized(resource1) {
      System.out.println("Thread 1: locked resource 1");

      // Pause for a bit, simulating some file I/O or something.
      // Basically, we just want to give the other thread a chance to
      // run.  Threads and deadlock are asynchronous things, but we're
      // trying to force deadlock to happen here...
      try { Thread.sleep(50); } catch (InterruptedException e) {}

      // Now wait 'till we can get a lock on resource 2
      synchronized(resource2) {
        System.out.println("Thread 1: locked resource 2");
      }
    }
  }
};

// Here's the second thread.  It tries to lock resource2 then resource1
Thread t2 = new Thread() {
  public void run() {

    // This thread locks resource 2 right away
     synchronized(resource2) {
      System.out.println("Thread 2: locked resource 2");

      // Then it pauses, for the same reason as the first thread does
      try { Thread.sleep(50); } catch (InterruptedException e) {}

      // Then it tries to lock resource1.  But Thread 1 locked
      // resource1, and won't release it till it gets a lock on
      // resource2.  This thread holds the lock on resource2, and won't
      // release it 'till it gets resource1. 
      synchronized(resource1) {
        System.out.println("Thread 2: locked resource 1");
      }
    }
  }
};


// t3 tries to lock resource3 then resource2
Thread t3 = new Thread() {
  public void run() {
      for(int i=1; i<=5;i++)
        System.out.println("t3 "+i);
    synchronized (resource3) {
      System.out.println("Thread 3: locked resource 3");

      try {
        Thread.sleep(50);
      } catch (InterruptedException e) {
      }

      synchronized (resource2) {
        System.out.println("Thread 3: locked resource 2");
      }
    }
  }
};

现在我想做的是模拟死锁,我猜程序停止导致死锁。

问题出现后,我添加了一个 for 循环,在synchronized函数之前的每个线程中打印一些文本。但是当我为每个线程设置优先级时,setPriority我没有看到线程根据它们的优先级完成工作。

例如,我在第一个线程之前的每个线程中都有这些 forloops synchronized

for(int i=1; i<=5;i++)
   System.out.println("t2 "+i);

依此类推,t2 代表线程 2。我要做的就是确保优先级正常工作。我还没有尝试在非死锁程序中根据线程的优先级运行线程。

操作系统或 CPU 可能是导致此类问题的原因?

最后,我的最后一个问题是,我能否在资源、打印和执行时间方面显示优先效果?

谢谢 :)

4

1 回答 1

2

大多数通用操作系统上的线程优先级不是绝对的(例如,准备运行的最高优先级线程总是获得 CPU),而是一个调度算法的输入,该算法计算一个量子 - 或允许线程运行之前的时间长度将控制权交给另一个人。

因此,即使您确实设置了优先级,也无法确定您的线程将运行的顺序。您可以放心地假设最高优先级的线程可能比优先级较低的线程获得更大的 CPU 时间份额。但是,由于您的程序正在执行重复的 IO(哪些阻塞)然后休眠,因此线程很可能无论如何都无法接近它们的量子,并且在 50 毫秒的休眠结束时都同样有资格运行。

一类操作系统——实时操作系统(RTOS)——确实实现了优先级驱动的抢占式线程行为(而不是时间片),并且可以产生高度可预测的线程顺序。

于 2013-01-13T00:59:24.513 回答