如何在java线程中优先考虑

时间:2013-07-09 20:13:18

标签: java multithreading

我正在尝试优先考虑线程b,但它仍然无法工作,有时候在优先级不起作用之前打印线程t,我不确定代码是否有任何帮助!

public static void main(String[] args) throws Exception {
    Thread t = new Thread(new one("this is t thread"));
    Thread b = new Thread(new one("this is b thread"));

    b.setPriority(10);
    t.setPriority(4);

    t.start();
    b.start();
}    


class one implements Runnable {
    String name;

    public one(String n) {
        name = n;
    }

    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(name);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

线程,即使是优先级,也是独立设计的。没有锁定,你无法保证任何事情。

您可以创建任何对象并将其命名为lockObject。

然后您可以启动线程,并在打印前调用lockObject.wait()

线程b然后调用它的print和然后调用lockObject.notify(),确保它是同一个对象的同一个实例(只在你的类中声明为static Object lockObject=new Object())< / p>

如果线程t开始击败线程b,它将等待通知。在此通知触发之前,t必须已打印。

这不是一种最佳方法,但对于这个问题应该足够了