Java多线程:无法更改线程优先级
我有两个线程,它们的优先级是使用Java多线程:无法更改线程优先级,java,multithreading,Java,Multithreading,我有两个线程,它们的优先级是使用setPriority()函数设置的,但它仍然显示相同的优先级 以下是代码片段: public class threadtest extends Thread { public void run() { System.out.println("running thread name is:" + Thread.currentThread().getName()); System.out.println("running thr
setPriority()
函数设置的,但它仍然显示相同的优先级
以下是代码片段:
public class threadtest extends Thread {
public void run() {
System.out.println("running thread name is:" + Thread.currentThread().getName());
System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
threadtest tt = new threadtest();
tt.setPriority(MAX_PRIORITY);
threadtest tt1 = new threadtest();
tt1.setPriority(MIN_PRIORITY);
tt1.run();
tt.run();
}
}
如果myECLIPSE neon中的上述代码为,则输出为
running thread name is:main
running thread priority is:5
running thread name is:main
running thread priority is:5
即使优先级不同,它也会显示相似的优先级。您应该调用
Thread.start()
,而不是Thread.run()
直接调用run()
方法时,run()
方法中的代码不会在新线程上执行,而是在同一线程上执行。另一方面,当调用Thread.start()
方法时,run()
方法中的代码将在新线程上执行,新线程实际上是由start()
方法创建的:
public class threadtest extends Thread {
public void run() {
System.out.println("running thread name is:" + Thread.currentThread().getName());
System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
threadtest tt = new threadtest();
tt.setPriority(MAX_PRIORITY);
threadtest tt1 = new threadtest();
tt1.setPriority(MIN_PRIORITY);
tt1.start();
tt.start();
}
}
输出:
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:10
running thread priority is:1
您应该调用
Thread.start()
,而不是Thread.run()
直接调用run()
方法时,run()
方法中的代码不会在新线程上执行,而是在同一线程上执行。另一方面,当调用Thread.start()
方法时,run()
方法中的代码将在新线程上执行,新线程实际上是由start()
方法创建的:
public class threadtest extends Thread {
public void run() {
System.out.println("running thread name is:" + Thread.currentThread().getName());
System.out.println("running thread priority is:" + Thread.currentThread().getPriority());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
threadtest tt = new threadtest();
tt.setPriority(MAX_PRIORITY);
threadtest tt1 = new threadtest();
tt1.setPriority(MIN_PRIORITY);
tt1.start();
tt.start();
}
}
输出:
running thread name is:Thread-0
running thread name is:Thread-1
running thread priority is:10
running thread priority is:1