java - 在 Java 中等待通知

标签 java multithreading thread-priority

class Callme {
    void call(String msg) {
        System.out.print("[" + msg);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }
        System.out.println("]");    
    }
}    

class Caller implements Runnable {
    String msg;
    Callme target;
    Thread t;
    public Caller(Callme targ, String s) {
        target = targ;
        msg = s;
        t = new Thread(this);
        t.start();
    }

    public void run() {
        //synchronized(target){ // synchronized block
        target.call(msg);
        //}
    }
}
class Synch {
    public static void main(String args[]) {
        Callme target = new Callme();
        Caller ob1 = new Caller(target, "Hello");
        ob1.t.setPriority(Thread.NORM_PRIORITY);
        Caller ob2 = new Caller(target, "Synchronized");
        Caller ob3 = new Caller(target, "World");
        ob2.t.setPriority(Thread.MAX_PRIORITY);
        ob3.t.setPriority(Thread.MIN_PRIORITY);
        System.out.println(ob1.t.getPriority());
        System.out.println(ob2.t.getPriority());
        System.out.println(ob3.t.getPriority());
        // wait for threads to end
        try {
            ob1.t.wait();
            ob2.t.wait();
            ob3.t.wait();
            ob1.t.notifyAll();

        } catch(InterruptedException e) {
            System.out.println("Interrupted");
        }
    }
}

鉴于我们优先考虑子线程,并且使用了 wait()notifyall() 方法,因此必须根据优先级运行。但不能跑。如果我们也使用synchronized(target),那么也不会根据优先级运行。

最佳答案

Tread.setPriority() 更改线程的执行优先级,这意味着更高优先级的线程在运行时更有可能被选中执行(与并发运行的较低优先级相比线)。当然,如果你通过显式调用 wait() 来停止线程,它在等待时不会运行,所以在这种情况下优先级是没有意义的。

更新:如上所述,优先级用于运行 线程。当您调用 notify() 时,所选择的线程不是基于优先级的(至少不能保证如此,规范没有说明这种或那种方式)

关于java - 在 Java 中等待通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10633326/

相关文章:

java - 在 Java (Jython) 中使用 python 代码出现问题

java.net.ConnectException : Tried all: '1' addresses, 但无法通过 HTTP 连接到服务器

java - 我如何检查在同一个jsp页面中提交的jsp表单请求? (加密类型 ="multipart/form-data")

java - 成功执行安全关机后,服务器会频繁启动/停止。怎么了?

c++ - 使用 Code::Blocks GNU 编译器编译多线程代码

c - 与 POSIX 系统上的调度有关的互斥体和线程优先级

java - 尝试用 java 读取文本文件 - 错误 : File of directory does not exist - LINUX

multithreading - 基于Windows Phone 8的线程

c# - 更改线程优先级

c - 基于优先级的多线程?