设置优先级
在Java多线程中,可以通过对线程设置优先级的方法,来调节线程被优先执行的概率。
package cn.edu.Lab;
class MyThread extends Thread {
public MyThread(String s) {
this.setName(s);
}
public void run() {
for(int i = 0; i < 6; i++) {
System.out.println("Here is " + getName());
}
}
}
public class Day1 {
public static void main(String[] args) {
MyThread t1 = new MyThread("Johnny");
MyThread t2 = new MyThread("Johnson");
t1.setPriority(10);
t2.setPriority(1);
t1.start();
t2.start();
}
}
守护线程
守护线程,即为其他线程服务的线程;当其他线程运行结束后,守护线程也会随之结束。
package cn.edu.Lab;
class MyThread extends Thread {
public MyThread(String s) {
this.setName(s);
}
public void run() {
for(int i = 0; i < 6; i++) {
System.out.println("Here is " + getName());
}
}
}
public class Day1 {
public static void main(String[] args) {
MyThread t1 = new MyThread("Johnny");
MyThread t2 = new MyThread("Johnson");
t2.setDaemon(true);
t1.start();
t2.start();
}
}
出让线程
顾名思义,就是让当前执行的线程出让CPU
class MyThread extends Thread {
public MyThread(String s) {
this.setName(s);
}
public void run() {
for(int i = 0; i < 6; i++) {
System.out.println("Here is " + getName());
Tread.yield();
}
}
}
本文介绍了如何在Java中为线程设置优先级,区分普通线程和守护线程,以及出让线程的使用。通过示例展示了如何使用`setPriority`方法调整线程优先级,守护线程如何随主线程结束而终止,以及`yield()`方法出让CPU资源。
234

被折叠的 条评论
为什么被折叠?



