Java------多线程_深度观察状态_优先级_守护线程(六)

Java------多线程_深度观察状态_优先级_守护线程(六)
常用其他方法
isAlive():判断线程是否还活着,即线程是否还未终止,boolean类型
setName():给线程起一个名字,
getName():获取线程的名字
currentThread():取得当前正在运行的线程对象,也是获取自己本身,静态方法。
深度观察状态
就绪状态和运行状态在计算机中都显示为Runnable。
State对象,Thread.state,线程状态的类
在java文档中,又将线程状态细分。分为6种状态
1.New,即新生状态,尚未启动的线程处于该状态。
2.Runnable,包括就绪和运行状态
3.BLOCKED,阻塞中的IO、waite。
4.waiting,阻塞中的sleep。
5.timed_waiting,阻塞中的有时间的sleep,正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
6.terminated,退出线程处于该状态
案例代码:

/**
 * 观察线程状态
 */
public class ThreadState {
    
    
    public static void main(String[] args) {
    
    
        Thread thread = new Thread(() ->{
            System.out.println("线程..............");
        });
        //观察线程状态
        Thread.State state = thread.getState();
        //此时处于新生状态 new
        System.out.println(state);
        thread.start();
        //此时处于runnable状态
        System.out.println(thread.getState());
        //加入sleep(100),则属于timed_wating
        System.out.println(thread.getState());
        //活动线程数,目前是主线程,和开辟的线程,因此有两个,如果执行子线程执行完了,则有1个
        int i = Thread.activeCount();
        System.out.println(i);
    }
}

优先级priority
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照线程的优先级决定应调度哪个线程来执行。
线程优先级从0到10表示。超过该范围就会报错。
API中有三个常量,也可以直接写数字
MIN_PRIORITY = 1
MAX_PRIORITY = 10
NORM_PRIORITY = 5
优先级的设定建议在start()调用前
注:优先级低只是意味着获得调度的概率低,并不是绝对先调用优先级高后调用优先级低的线程。
案例代码:

public class ThreadPriority{
    
    
    public static void main(String[] args) {
    
    
        Thread thread1 = new Thread(new MyPRIORITY());
        Thread thread2 = new Thread(new MyPRIORITY());
        Thread thread3 = new Thread(new MyPRIORITY());
        Thread thread4 = new Thread(new MyPRIORITY());
        Thread thread5 = new Thread(new MyPRIORITY());
        //也可以直接写数字
        thread1.setPriority(Thread.MIN_PRIORITY);
        thread2.setPriority(Thread.MAX_PRIORITY);
        thread3.setPriority(Thread.NORM_PRIORITY);
        thread4.setPriority(Thread.MAX_PRIORITY);
        thread5.setPriority(Thread.MIN_PRIORITY);

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        //打印结果
        //Thread-1--->10
        //Thread-3--->10
        //Thread-2--->5
        //Thread-0--->1
        //Thread-4--->1
    }
}

class MyPRIORITY implements Runnable{
    
    

    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
    }
}

守护线程Daemon
线程分为用户线程守护线程
虚拟机必须确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕
如后台记录操作日志、监控内存使用等。
只需要 **thread.setDaemon(true)**即可将线程标记为守护线程,默认为false。设置为守护线程后,jvm不会等该线程结束。

猜你喜欢

转载自blog.csdn.net/cz_chen_zhuo/article/details/121647829