一步步学习多线程(三) 多线程基础2(守护线程、优先级)

守护线程

在后台默默地完成一些系统性的服务,比如垃圾回收线程,JIT线程就可以理解为守护线程

当一个Java应用内,只有守护线程时,Java虚拟机就会自然退出。

例子:

public class DeaonDemo {
public static class DaemonT extends Thread {

@Override
public void run() {
while(true){
System.out.println("I am alive");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}
public static void main(String[] args){
Thread t1 = new DaemonT();
t1.setDaemon(true);
t1.start();
}
}

在上述例子中,运行的结果就是有可能会输出1-2条"I am alive",也可有什么也没有输出就结束了,因为守护进程并不能让虚拟机持续运行下去。


线程优先级

1、当线程的优先级没有指定时,所有线程都携带普通优先级。

2、优先级可以用从1到10的范围指定。10表示最高优先级,1表示最低优先级,5是普通优先级。

3、优先级最高的线程在执行时被给予优先。但是不能保证线程在启动时就进入运行状态。

4、t.setPriority()用来设定线程的优先级

5、Java线程的优先级是一个整数,其取值范围是1 (Thread.MIN_PRIORITY ) - 10 (Thread.MAX_PRIORITY )

例子如下:

public class PriorityDemo {

public static class HighPriority extends Thread {
static int count = 1;
@Override
public void run() {
while(true){
synchronized (PriorityDemo.class) {
count++;
if(count>=10000000){
System.out.println("high:" + count);
break;
}
}
}
}
}
public static class LowPriority extends Thread {
static int count = 1;

@Override
public void run() {
while(true){
synchronized (PriorityDemo.class) {
count++;
if(count>=10000000){
System.out.println("low:" + count);
break;
}
}
}
}
}
public static void main(String[] args) {
HighPriority high = new HighPriority();
LowPriority low = new LowPriority();
high.setPriority(Thread.MAX_PRIORITY);
low.setPriority(Thread.MIN_PRIORITY);
low.start();
high.start();
}
}

执行的结果:

high:10000000
low:10000000

猜你喜欢

转载自blog.csdn.net/money9sun/article/details/80419348