一. Thread 的静态优先级常量
一.一 静态常量
一. 二 演示 优先级常量
@Test public void staticTest(){ System.out.println("max:"+Thread.MAX_PRIORITY); System.out.println("norm:"+Thread.NORM_PRIORITY); System.out.println("min:"+Thread.MIN_PRIORITY); }
运行测试,查看控制台:
运行测试,查看控制台:
二.一.二 演示构造方法
@Test public void conTest(){ //空构造 Thread thread=new Thread(); //传入名称 Thread thread1=new Thread("自定义线程"); //传入Runnable Thread thread2=new Thread(new MyRunnable()); //4 传入Runnable 和name Thread thread3=new Thread(new MyRunnable(),"自定义Runnable接口"); }
二.二 其他方法
三. 演示线程名称 getName()
@Test public void nameTest() throws Exception{ NameThread nameThread=new NameThread(); Thread thread1=new Thread(nameThread); //默认的为 Thread-接下来的数据, 从0开始。 Thread thread2=new Thread(nameThread,"自定义线程"); Thread thread3=new Thread(nameThread); Thread thread4=new Thread(nameThread,"两个蝴蝶飞,你好"); thread1.start(); thread2.start(); thread3.start(); thread4.start(); // main, main方法也是一个线程 System.out.println("当前线程的名称:"+Thread.currentThread().getName()); } class NameThread implements Runnable{ @Override public void run() { for(int i=0;i<5;i++){ System.out.println("当前线程:"+Thread.currentThread().getName()+"正在运行,输出:"+i); } } }
运行程序,控制台打印输出
如果不传入线程的名称, 则线程的名称系统自分配为: Thread-不重复数字
四. 获取线程的信息
四.一 主线程状态
@Test public void readMainTest() throws Exception{ //1. 获取当前的主线程 Thread thread=Thread.currentThread(); System.out.println("当前线程的名称:"+thread.getName()); System.out.println("获取标识符 id:"+thread.getId()); System.out.println("获取优先级:"+thread.getPriority()); System.out.println("获取状态:"+thread.getState()); System.out.println("当前线程是否还活着:"+thread.isAlive()); System.out.println("是否被中断:"+thread.isInterrupted()); System.out.println("是否是守护线程:"+thread.isDaemon()); //可以手动设置名称和优先级 thread.setName("手动设置名称"); thread.setPriority(Thread.MAX_PRIORITY); System.out.println("当前线程的名称:"+thread.getName()); System.out.println("获取优先级:"+thread.getPriority()); //设置守护线程,必须要在线程运行之前进行设置 }
运行程序,看控制台输出:
四.二 Runnable 线程状态
@Test public void readNoTest() throws Exception{ ReadRunnable readRunnable=new ReadRunnable(); Thread thread=new Thread(readRunnable); thread.start(); } class ReadRunnable implements Runnable{ @Override public void run() { Thread thread=Thread.currentThread(); System.out.println("当前线程的名称:"+thread.getName()); System.out.println("获取标识符 id:"+thread.getId()); System.out.println("获取优先级:"+thread.getPriority()); System.out.println("获取状态:"+thread.getState()); System.out.println("当前线程是否还活着:"+thread.isAlive()); System.out.println("是否被中断:"+thread.isInterrupted()); System.out.println("是否是守护线程:"+thread.isDaemon()); //可以手动设置名称和优先级 thread.setName("手动设置名称"); thread.setPriority(Thread.MAX_PRIORITY); System.out.println("当前线程的名称:"+thread.getName()); System.out.println("获取优先级:"+thread.getPriority()); } }
运行程序,控制台打印输出: