多线程(2)- 线程API
前言
主要包括线程API方法使用及说明扩展:
概念
- 进程: 计算机的一个任务就是一个进程。
- 线程:进程的最下执行单元,每个进程至少要有一个线程是在运行中。
1、sleep
不会放弃monitor锁的所有权
TimeUnit.sleep 代替 Thread.sleep
线程状态:RUNNING - BLOCK
public void sleep() throws InterruptedException {
//指定线程休眠10时20分30秒
Thread.sleep((10*3600+20*60+30)*1000);
//TimeUnit方式
TimeUnit.HOURS.sleep(10);
TimeUnit.MINUTES.sleep(20);
TimeUnit.SECONDS.sleep(30);
}
2、yield
使用场景较少,提醒调度器放弃CPU资源,如果CPU资源不紧张则会放弃这种提醒
线程状态:RUNNABLE - RUNNING
static class ThreadYield{
public static void yield(){
IntStream.range(0,2).mapToObj(ThreadYield::test).forEach(Thread::start);
}
public static Thread test(int index){
return new Thread(()->{
System.out.println(index);
});
}
}
static class ThreadYield{
public static void yield(){
IntStream.range(0,2).mapToObj(ThreadYield::test).forEach(Thread::start);
}
public static Thread test(int index){
return new Thread(()->{
if (index == 0){
Thread.yield();
}
System.out.println(index);
});
}
}
3、setPriority
设置线程优先级,不一定生效,在CPU忙的时候可能会获得更多的CPU时间片
默认main线程优先级 = 5
范围1 <= proority <= 10
线程默认优先级与父优先级一样
如果线程优先级设置大于线程组优先级,会使用线程组优先级
static class ThreadPriority{
public static void setPriority(){
System.out.println(Thread.currentThread().getName() +" 优先级:"+ Thread.currentThread().getPriority());
Thread t = new Thread(()->{
System.out.println(Thread.currentThread().getName() +" 优先级:"+ Thread.currentThread().getPriority());
subThreadSetPriority();
},"priority-1");
t.setPriority(6);
t.start();
}
public static void subThreadSetPriority(){
new Thread(()->{
System.out.println(Thread.currentThread().getName() +" 优先级:"+ Thread.currentThread().getPriority());
},"priority-2").start();
}
}
public static void main(String[] args) {
//testYield();
testPriority();
}
main 优先级:5
priority-1 优先级:6
priority-2 优先级:6
4、interrupt
一个线程内部维护着interrupted flag 标识 、如果一个线程被interrupt,那么他的flag被设置
但是当线程正在执行可中断方法被阻塞时,调用interrupt方法将其中断,反而会导致flag被清除,此时interrupt()会返回false
如果一个线程时死亡状态,那么interrupt将被忽略
- 可中断方法(使当前线程进入阻塞的方法,当其他线程调用阻塞线程的interrupt,会打断线程阻塞,仅仅打断打断阻塞并不意味着线程周期结束):
Object.wait
Thread.sleep
Thread.join
其他方法
线程中断
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(()->{
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " 被中断 ");
}
});
t.start();
//short block and make sure thread is started.
TimeUnit.SECONDS.sleep(1);
t.interrupt();
}
Thread-0 被中断
非可中断方法,正常运行结果
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (true) {
// try {
// System.out.println(Thread.currentThread().getName() + " 1 " + Thread.currentThread().isInterrupted());
// //可中断方法
// TimeUnit.MINUTES.sleep(1);
// } catch (InterruptedException e) {
// System.out.println(Thread.currentThread().getName() + " 被中断 ");
// }
}
});
//设置为守护线程,JVM主线程跑完了因为没有非守护线程而自动退出
t.setDaemon(true);
t.start();
TimeUnit.SECONDS.sleep(1);
System.out.println(t.getName() + " 3 " + t.isInterrupted());
t.interrupt();
TimeUnit.SECONDS.sleep(1);
System.out.println(t.getName() + " 4 " + t.isInterrupted());
}
Thread-0 3 false
Thread-0 4 true
可中断方法清除interrupt标记
可中断方法捕获到中断信号,会擦除interrupt标识,因此程序的执行结果都会是false
public class ThreadInterrupt {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(() -> {
while (true) {
try {
System.out.println(Thread.currentThread().getName() + " 1 " + Thread.currentThread().isInterrupted());
//可中断方法
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " 被中断 ");
}
}
});
//设置为守护线程,JVM主线程跑完了因为没有非守护线程而自动退出
t.setDaemon(true);
t.start();
TimeUnit.SECONDS.sleep(1);
System.out.println(t.getName() + " 3 " + t.isInterrupted());
t.interrupt();
TimeUnit.SECONDS.sleep(1);
System.out.println(t.getName() + " 4 " + t.isInterrupted());
}
}
Thread-0 1 false
Thread-0 3 false
Thread-0 被中断
Thread-0 1 false
Thread-0 4 false
Thread.interrupted(),如果产生中断,会擦除interrupt标识
判断到了中断,第一次返回true,其后一直返回false,除非后面再次进行中断又会返回一个true
Thread t = new Thread(() -> {
while (true) {
System.out.println(Thread.interrupted());
}
});
t.setDaemon(true);
t.start();
TimeUnit.MILLISECONDS.sleep(2);
t.interrupt();
在可中断方法执行前就已经中断,此时再执行可中断方法是怎样的
private static void testInterrupt() {
//在可中断方法前就已经中断,此时再执行可中断方法是怎样的
//擦除interrupt 标识复位
System.out.println("1 has interrupt ? " + Thread.interrupted());
Thread.currentThread().interrupt();
//判断是否中断,不能擦除interrupt标识
System.out.println("2 has interrupt ? " + Thread.currentThread().isInterrupted());
try {
//a
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
System.out.println(" has interrupt " + e.getMessage());
}
//a处执行可中断方法,所以此时已擦除interrupt标识,返回false
System.out.println("3 has interrupt ? " + Thread.currentThread().isInterrupted());
}
1 has interrupt ? false
2 has interrupt ? true
has interrupt sleep interrupted
3 has interrupt ? false
5、join
public class ThreadJoin {
public static void main(String[] args) throws InterruptedException {
List<Thread> threads = IntStream.range(1, 3).mapToObj(ThreadJoin::createThread).collect(Collectors.toList());
threads.forEach(Thread::start);
for (Thread t : threads) {
//主线程中join两个线程,会使主线程阻塞,直到两个线程都执行完成
t.join();
}
for (int i = 0; i < 10; i++) {
shortSleep();
System.out.println(Thread.currentThread().getName() + "#" + i);
}
}
private static Thread createThread(int seq) {
Thread t = new Thread(() -> {
for (int i = 0; i < 10; i++) {
shortSleep();
System.out.println(Thread.currentThread().getName() + "#" + i);
}
}, String.valueOf(seq));
return t;
}
private static void shortSleep() {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
;
}
}
2#0
1#0
……
1#9
2#9
main#0
……
main#9
6、线程正常结束
1、线程结束生命周期正常结束
2、捕获中断信号关闭线程
通过interrupt标识关闭线程
3、使用volatile开关控制
volatile:可见性 有序性
4、异常退出
5、进程假死