设置优先级
在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();
}
}
}