【Java学习笔记】线程的命名、休眠与优先级

xiaoxiao2021-02-28  35

线程的命名与取得

利用Thread类可以为线程命名。

public Thread(Runnable target, String name); //构造方法 public final void setName(String name); //命名 public final String getName(); //取得

但如果使用Runnable接口,想要取得线程名称名字,那么能够先取得的就是当前执行本方法的线程:

public static Thread currentThread(); //获得当前的线程对象

实例化Thread类对象时,如果没有进行命名,那么会自动进行编号命名(从-0开始,到-n,主方法的线程名是main,main线程也只是进程的子线程)。

每个JVM进程启动的时,至少启动几个线程?

main线程:程序的主要执行,以及启动子线程;gc线程:负责垃圾收集。

休眠

线程休眠可以使线程的执行速度稍微变慢一点,休眠的方法:

public static void sleep(long millis) throws InterruptedException

示例:

class MyThread implements Runnable{ public void run() { for(int i = 0; i < 100000; i++) { //休眠0.1秒 try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" i = "+i); } } } public class TestMain { public static void main(String[] args) throws InterruptedException, ExecutionException{ MyThread mt = new MyThread(); new Thread(mt,"线程A").start(); } }

当多个线程休眠后同时唤醒,它们的执行顺序也是不同的,所以这会涉及到线程优先级与线程同步的问题。

线程优先级

越高的优先级,越有可能先执行。只是越有可能先执行!

Thread类中提供有以下方法:

public final void setPriority(int newPriority); //设置优先级 public final int getPriority(); //取得优先级

优先级都是int数据类型常量:

最高优先级:MAX_PRIORITY = 10中等优先级:NORM_PRIORITY = 5最低优先级:MIN_PRIORITY = 1 public class TestMain { public static void main(String[] args) throws InterruptedException, ExecutionException{ MyThread mt = new MyThread(); Thread t1 = new Thread(mt,"线程A"); t1.setPriority(Thread.MAX_PRIORITY); Thread t2 = new Thread(mt,"线程B"); t2.setPriority(Thread.NORM_PRIORITY); Thread t3 = new Thread(mt,"线程C"); t3.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); t3.start(); } }

主线程的优先级?

主线程属于中等优先级,即NORM_PRIORITY = 5。

转载请注明原文地址: https://www.6miu.com/read-2612468.html

最新回复(0)