java线程优先级有什么意义?
来源:百度知道 编辑:UC知道 时间:2024/06/07 09:29:34
给线程设置了高优先级仍然不能保证他被最先执行完,那么优先级到底有什么用处?
例如:
class CustomThread extends Thread {
CustomThread(String name) {
super(name);
}
public synchronized void run() {
System.out.println(this.getName());
try {
sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("NAME: " + this.getName() + " Bye");
}
}
class MultiThread {
public static void main(String args[]) throws InterruptedException {
CustomThread thread1 = new CustomThread("first");
CustomThread thread2 = new CustomThread("second");
CustomThread thread3 = new CustomThread("third");
CustomThread thread4 = new CustomThread("fourth");
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY-1);
thread3.setPriority(Thread.MAX_PRIORITY-2);
例如:
class CustomThread extends Thread {
CustomThread(String name) {
super(name);
}
public synchronized void run() {
System.out.println(this.getName());
try {
sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("NAME: " + this.getName() + " Bye");
}
}
class MultiThread {
public static void main(String args[]) throws InterruptedException {
CustomThread thread1 = new CustomThread("first");
CustomThread thread2 = new CustomThread("second");
CustomThread thread3 = new CustomThread("third");
CustomThread thread4 = new CustomThread("fourth");
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MAX_PRIORITY-1);
thread3.setPriority(Thread.MAX_PRIORITY-2);
》》。。。而sleep之后就会随机排序了,优先级此时就不起作用了,有没有解决的办法?
其中一个办法是让每一个线程记得必须比它先完成的另一个线程,
然后在必要时强制它放弃执行一直到那另一个线程执行完为止。 比如:
class CustomThread extends Thread {
private Thread 先完;
CustomThread(String name, Thread 先完) {
super(name);
this.先完 = 先完;
}
public void run() {
System.out.println(this.getName());
try {
sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);