线程的优先级、继承性、守护线程
线程的优先级越高,越有可能先执行而已(仅为建议)
1.1 设置优先级
public final void setPriority(int newPriority)
1.2 取得优先级
public final int getPriority()
1.2.1 JDK内置优先级
1.最高优先级 : public final static int MAX_PRIORITY=10;
2.中等优先级:public final static int NORM_PRIORITY=5;
3.最低优先级: public final static int MIN_PRIORITY=1;
代码实现:设置优先级
package ThreadTest.PriorityTest;
/**
* @Name:设置优先级
* @Author:ZYJ
* @Date:2019-05-29-14:11
* @Description:
*/
public class PriorityDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread t1 = new Thread(myThread);
Thread t2 = new Thread(myThread);
Thread t3 = new Thread(myThread);
//设置优先级
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.NORM_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);
t1.start();
t2.start();
t3.start();
}
}
class MyThread implements Runnable{
@Override
public void run() {
for(int i=0;i<5;i++){
System.out.println("当前线程为"+Thread.currentThread().getName()+",i="+i);
}
}
}
主方法是一个中等优先级;
2.线程的继承性
若在一个线程中创建了子线程,默认子线程与父线程的优先级相同
必如在A线程中启动了B线程,那么B的优先级和A一样;
package ThreadTest.ThreadExtends;
/**
* @Name: 线程的优先级问题。
* @Author:ZYJ
* @Date:2019-05-29-14:21
* @Description: 优先级的继承性
*/
class A implements Runnable{
@Override
public void run() {
System.out.println("A的优先级:"+Thread.currentThread().getPriority());
Thread thread = new Thread(new B());
thread.start();
}
}
class B implements Runnable{
@Override
public void run() {
System.out.println("B的优先级:"+Thread.currentThread().getPriority());
}
}
public class ThreadExtendsDemo {
public static void main(String[] args) {
Thread thread = new Thread(new A());
//将A线程的优先级设置为最高优先级
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
}
}
3. 守护线程
java中线程分为两类:用户线程、守护线程 通过isDaemon()
方法区分他们:如果返回false,则说明该线程是“用户线程”;如果返回true,则说明该线程是“守护线程”.
守护线程为陪伴线程,只要JVM中存在由任何一个用户线程没有终止,守护线程就一直在工作。
**默认创建的线程都有用户线程,主线程也为用户线程。**通过setDaemon(true)
将线程对象设置为守护线程。
典型的守护线程:垃圾回收线程(随着线程开始而开始,随着线程结束而结束)
package ThreadTest.DaemonTest;
/**
* @Name:观察守护线程
* @Author:ZYJ
* @Date:2019-05-29-14:33
* @Description: 守护线程在所有线程执行结束后结束
*/
public class DaemonDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(new A(), "子线程A");
//将线程A 设置为守护线程 ,此语句必须在start方法之前执行
thread1.setDaemon(true);
thread1.start();
Thread thread2 = new Thread(new A(), "子线程B");
thread2.start();
Thread.sleep(3000);
//中断非守护线程
thread2.interrupt();
Thread.sleep(10000);
System.out.println("代码结束");
}
}
class A implements Runnable {
private int i;
@Override
public void run() {
try {
while (true) {
i++;
System.out.println("线程名称" + Thread.currentThread().getName() +
",i=" + i + ",是否为守护线程" + Thread.currentThread().isDaemon());
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("线程名称:" + Thread.currentThread().getName() + "线程中断");
}
}
}