两种线程实现方式没有区别
在java
中,有实现Runnable
接口和集成Thread
类两种实现线程的方式,但是在线程的运行过程中,这两种实现方式并没有区别,因为在最终启动线程时,都需要调用Thread
类对象的start
方法。
核心方式
currentThread
currentThread
方法用于获取当前正在执行的线程,即当前代码段正在被哪个线程调用
Thread.currentThread()
isAlive
isAlive
方法用于判断当前线程是否处于存活状态
public static void main(String[] args) throws Exception{
Thread t = new Thread(()->{
System.out.println( "线程内 " + Thread.currentThread().isAlive());
});
System.out.println( "启动前 " + t.isAlive());
t.start();
System.out.println( "启动后 " + t.isAlive());
TimeUnit.SECONDS.sleep(1);
System.out.println("最后 " + t.isAlive());
}
执行结果:
线程的优先级
在操作系统中,线程可以划分优先级,CPU会优先执行优先级较高的线程对象中的任务,但是线程的优先级具有随机性,并不是优先级高的线程就一定会先执行完
- 设置线程的优先级
在Thread
类中生命了三种线程的优先级
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
调用setPriority
方法设置优先级
new Thread().setPriority(Thread.MAX_PRIORITY);
守护线程
守护线程只有在有非守护线程运行的情况下才能存在,如果进程中没有非守护线程了,守护线程也会自动销毁
new Thread().setDaemon(true);
join
join
方法表示等待被调用的线程执行完成之后,再执行自己
如在main
方法中,启动一个线程T
,此时我们共启动了两个线程,T
线程和main
线程,要实现必须等T
线程执行结束之后,才能让main
线程结束
public class ThreadJoin extends Thread{
@Override
public void run() {
for (int i=0;i<5;i++){
try {
TimeUnit.MILLISECONDS.sleep(500);
System.out.println(Thread.currentThread().getName() + " " + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadJoin t = new ThreadJoin();
t.setName("T");
t.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "执行结束");
}
}