Java多线程使用 sleep 和中断

标签 java multithreading synchronization sleep interrupt

class Useless {
    public static boolean b = true;

    public synchronized void u1() {
        try {
            while (b == true)
                wait();
        } catch (InterruptedException i) {
        }
    }

    public synchronized void u2() {
        if (b == true) {
            b = false;
        }
        notify();
    }
}

public class SleepMessages extends Thread {

private Useless u;

    public SleepMessages(Useless u) {
        this.u = u;
    }

    public void run() {
        String importantInfo[] = { "Mares eat oats", "Does eat oats" };
        for (int i = 0; i < importantInfo.length; i++) {
            u.u1();
            System.out.println(importantInfo[i] + " - " + getName());
            try {
                sleep(2000);
            } catch (InterruptedException e) {
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {
        Useless u = new Useless();
        Thread t1 = new SleepMessages(u);
        t1.setName("t1");
        Thread t2 = new SleepMessages(u);
        t2.setName("t2");
        t1.start();
        t2.start();
        sleep(2000);
        System.out.println("Here they go!...");
        t1.interrupt();
        sleep(1000);
        t2.interrupt();
        u.u2();
        sleep(1000);
        u.u2();
    }
}

这个小程序的输出给出: 他们来了!... 母马吃燕麦 - t1 母马吃燕麦 - t2 吃燕麦吗-t2 吃燕麦吗 - t1

我的问题是为什么线程 t2 是唯一进入 catch(InterruptedException e) 的线程,为什么结果不是这样的:

他们来了!... 母马吃燕麦 - t1 母马吃燕麦 - t2 吃燕麦吗 - t1 吃燕麦吗 - t2

最佳答案

My question is why does the thread t2 is the only one that enters the catch(InterruptedException e),

在我看来,t1.interrupt() 正在中断 run() 方法中的 sleep 。一旦丢弃 InterruptedException,就无法知道线程之前是否被中断过。

why isn't the result something like this: Here they go!... Mares eat oats - t1 Mares eat oats - t2 Does eat oats - t1 Does eat oats - t2

Java 使用偏向锁定。这意味着最后一个获取锁的线程更有可能首先获取相同的锁。

关于Java多线程使用 sleep 和中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14219306/

相关文章:

java - 无法通过 Java 运行时进程查看输出

javascript - ForEach(内部有异步函数)完成后的回调

.net - WCF 客户端-服务器同步 : Polling vs. 绑定(bind)

ios - 将本地 sqlite 文件同步到 iCloud

java - java.util.stream.Streamable 发生了什么?

java - 在mavenLocal()中为.jar文件成功添加gradle依赖关系之后,我如何实际从Java类导入和使用该jar

具有复杂类型定义的 Java Collections.synchronizedMap()

java - 为什么我的 map 坏了?

java - freemarker 无法处理谷歌应用引擎上的 '/' 请求

python - SQLAlchemy ORM : safely passing objects between threads without manually reattaching?