如文档所述


  在线程休眠时不会释放其持有的锁


但是我的代码片段演示了它确实释放了锁定

public class SynchronizationTest {

    public static void main(String[] args) {
        Common c = new Common();
        new PersonONE(c);
        new PersonTWO(c);
    }
}

class Common {
    private String message = "This is shared message";
    public String getMessage() {
        return message;
    }
}

class PersonONE extends Thread {
    private Common c;
    public PersonONE(Common c) {
        this.c = c;
        start();
    }
    @Override
    public void run() {
        synchronized (c.getClass()) {
            for (int i = 0; i < 5; i++) {
                System.out.println("PersonONE: " + c.getMessage());
                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException e) {}
            }
        }
    }
}

class PersonTWO extends Thread {
    private Common c;
    public PersonTWO(Common c) {
        this.c = c;
        start();
    }
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("PersonTWO: "+c.getMessage());
            try {
                Thread.sleep(100);
            } catch (InterruptedException e){}
        }
    }
}


输出量

PersonONE:这是共享消息
PersonTWO:这是共享消息
PersonONE:这是共享消息
PersonTWO:这是共享消息
PersonONE:这是共享消息
PersonTWO:这是共享消息
PersonONE:这是共享消息
PersonTWO:这是共享消息
PersonONE:这是共享消息
PersonTWO:这是共享消息

所以,问题是:我在哪里错了?

最佳答案

PersonTWO不会尝试获取锁。

请参见以下示例,该示例确实演示了睡眠不会释放锁。

private static class Locker implements Runnable {
    private final Object lock;
    private final String message;

    private Locker(final Object lock, final String message) {
        this.lock = lock;
        this.message = message;
    }

    @Override
    public void run() {
        try {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    System.out.println(message);
                    Thread.sleep(1000);
                }
            }
        }
        catch (InterruptedException ex) {

        }
    }
}

public static void main(String[] args) {
    final int numThreads = 2;
    final Object lock = new Object();
    for (int i=0;i<numThreads;i++) {
        new Thread(new Locker(lock, "Hello - " + i)).start();
    }
}

关于java - 当前正在运行的线程在 sleep 时是否持有锁?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31730110/

10-08 23:02