Thread类构造方法:
1.Thread();
2.Thread(String name);
3.Thread(Runable r);
4.Thread(Runable r, String name);
public class Test {
public static void main(String[] args) {
/*
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread("MyThread");
thread1.start();
thread2.start();
*/
MyRunnable run = new MyRunnable();
Thread thread3 = new Thread(run);
Thread thread4 = new Thread(run, "MyThread");
thread3.start();
thread4.start();
}
}
常用方法:
start();//启动线程
getId();//获得线程ID
getName();//获得线程名字
getPriority();//获得优先权
isAlive();//判断线程是否活动
isDaemon();//判断是否守护线程
getState();//获得线程状态
sleep(long mill);//休眠线程
join();//等待线程结束
yield();//放弃cpu使用权利
interrupt();//中断线程
currentThread();//获得正在执行的线程对象
守护线程:也叫精灵线程,当程序只剩下守护线程的时候就会退出。
守护线程 的作用类似在后台静默执行,比如JVM的垃圾回收机制,这个就是一个守护线程。而非守护线程则不会。
MyRunnable run = new MyRunnable();
Thread thread3 = new Thread(run);
Thread thread4 = new Thread(run, "MyThread");
//设置优先级别
// thread3.setPriority(1);
// thread3.setPriority(Thread.MAX_PRIORITY);
// thread4.setPriority(10);
thread3.setPriority(Thread.NORM_PRIORITY);
thread4.setPriority(Thread.NORM_PRIORITY);
//获得线程的优先级别
System.out.println(thread3.getPriority());
System.out.println(thread4.getPriority());
System.out.println("----------------------");
thread3.start();
thread4.start();
System.out.println("----------------------");
System.out.println("线程3是否活动:"+thread3.isAlive());
System.out.println("线程4是否活动:"+thread4.isAlive());
System.out.println("----------------------");
// thread3.setDaemon(true);//设置为守护线程,必须在启动之前设置
System.out.println("线程3是否是守护线程:"+thread3.isDaemon());
System.out.println("线程4是否是守护线程:"+thread4.isDaemon());
System.out.println("----------------------");
//获取线程状态
System.out.println("线程3的状态:"+thread3.getState());
System.out.println("线程4的状态:"+thread4.getState());
try {
thread4.join();//等待线程4的结束
} catch (InterruptedException e) {
e.printStackTrace();
}