第03章 Thread API详细介绍


3.1 线程sleep


3.1.1 sleep方法介绍


static void sleep(long millis)
static void sleep(long millis, int nanos)

sleep方法会使当前线程进入指定毫秒级的休眠,休眠有一个重要的特性,那就是其不会放弃monitor锁的所有权。

3.1.2 使用TimeUnit替代Thread.sleep


在JDK1.5以后,JDK引入了一个枚举TimeUnit类,其对sleep方法有很好的封装。
例如让一个线程休眠1天2小时14分钟12秒。

try {  
    TimeUnit.DAYS.sleep(1);  
    TimeUnit.HOURS.sleep(2);  
    TimeUnit.MINUTES.sleep(14);  
    TimeUnit.SECONDS.sleep(12);  
} catch (InterruptedException e) {  
    throw new RuntimeException(e);  
}

3.2 线程yield


3.2.1 yield方法介绍


yield方法属于一种启发式的方法,其会提醒调度器我愿意放弃当前的CPU资源,如果CPU的资源不紧张则会忽略这种提醒。

3.2.2 yield和sleep


  • sleep会导致当前线程暂停指定的时间,没有CPU时间片的消耗。
  • yield只是对CPU调度器的一个提示,如果CPU调度器没有忽略这个提示,它会导致线程上下文的切换。
  • sleep会使线程短暂block,会在给定的时间内释放CPU资源。
  • yield会使RUNNING状态的Thread进入RUNNABLE状态(如果CPU调度器没有忽略这个提示的话)。
  • sleep几乎百分之百地完成了给定时间的休眠,而yield的提示并不能一定担保。
  • 一个线程sleep另一个线程调用interrupt会捕获到中断信号,而yield则不会。

3.3 设置线程的优先级


3.3.1 线程优先级介绍


  • 对于root用户,它会hint操作系统你想要设置的优先级别,否则它会被忽略。
  • 如果CPU比较忙,设置优先级可能会获得更多的CPU时间片,但是闲时优先级的高低几乎不会有任何作用。

3.3.2 线程优先级源码分析


public final void setPriority(int newPriority) {  
    ThreadGroup g;  
    checkAccess();  
    if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {  
        throw new IllegalArgumentException();  
    }   if((g = getThreadGroup()) != null) {  
	        if (newPriority > g.getMaxPriority()) {  
	            newPriority = g.getMaxPriority();  
	        }        
        setPriority0(priority = newPriority);  
    }
}

3.4 获取线程ID


public long getId() : 获取线程的唯一ID。

3.5 获取当前线程


public Thread currentThread : 获取当前线程。

3.6 设置线程上下文类加载器


  • public ClassLoader getContextClassLoader()获取线程上下文的类加载器,简单来说就是这个线程是由哪个类加器加载的,如果是在没有修改线程上下文类加载器的情况下,则保持与父线程同样的类加载器。
  • public void setContextClassLoader(ClassLoadercl)设置该线程的类加载器,这个方法可以打破JAVA类加载器的父委托机制,有时候该方法也被称为JAVA类加载器的后门。

3.7 线程interrupt


3.7.1 interrupt


当前线程进入阻塞状态时,调用当前线程的interrupt方法,就可以打断阻塞。
一旦一个线程在阻塞的情况下被打断,都会抛出一个称为InterruptedException的异常,这个异常就像一个signal一样通知当前线程被打断了。
中断一个线程并不意味着线程的生命周期结束,仅仅是打断了当前线程的阻塞状态。

public static void testInterrupted() {  
    Thread thread = new Thread() {  
        @Override  
        public void run() {  
            try {  
                TimeUnit.SECONDS.sleep(2);  
            } catch (InterruptedException e) {  
                System.out.println("What can I say");  
            }  
        }  
    };  
    thread.start();  
    thread.interrupt(); // 中断这个线程  
}
输出 : 
What can I say

3.7.2 isInterrupted


isInterrupted : 判断一个线程是否被中断。
sleep方法是一个可中断方法,它会捕获中断信号,并且擦除interrupt标识。

public static Runnable runnable2 = () ->{  
    try {  
        TimeUnit.SECONDS.sleep(3);  
    } catch (InterruptedException e) {  
        System.out.println(Thread.currentThread().isInterrupted());  
    }  
};  
public static void testIsInterrupted(Runnable runnable) {  
    Thread thread = new Thread(runnable);  
    thread.start();  
    System.out.println(thread.isInterrupted());  
    try {  
        TimeUnit.SECONDS.sleep(1);  
    } catch (InterruptedException e) {  
        throw new RuntimeException(e);  
    }  
    thread.interrupt();  
}
输出 : 
false
false

3.7.3 interrupted


3.7.4 Interrupt注意事项


如果一个线程在调用可中断方法之前就被中断了,那么当它调用可中断方法时,会被直接中断。

package chapter03;  
  
public class Test02 {  
    public static void main(String[] args) {  
        System.out.println("判断当前线程是否被打断 : " + Thread.interrupted());  
        Thread.currentThread().interrupt();   // 中断当前线程  
        System.out.println(Thread.currentThread().isInterrupted()); // 再次判断当前线程是否被中断  
  
        try {  
            Thread.sleep(400);  // 执行一个可中断方法  
        } catch (InterruptedException e) {  
            System.out.println("haha");  
        }  
    }  
}
输出 : 
判断当前线程是否被打断 : false
true
haha

3.8 线程join


Thread中的join方法也是一个可中断方法。

3.8.1 线程join方法详解


join某个线程A,会使当前线程B进入等待,直到线程A结束生命周期,或者到达给定的时间,在此期间线程B是BLOCKED的。

package chapter03;  
  
import java.util.Collections;  
import java.util.List;  
import java.util.stream.Collectors;  
import java.util.stream.IntStream;  
  
public class ThreadJoin {  
  
    public static void main(String[] args) {  
        // 生成一个拥有两个线程的列表  
        List<Thread> threads = IntStream.rangeClosed(1, 3).mapToObj(ThreadJoin::creat).collect(Collectors.toList());  
        threads.forEach(Thread::start); // 线程~~~, 启动!!!  
  
//        for (Thread thread : threads) { // 对于流的操作是不能处理异常的, 但我给它包装一下  
//            try {  
//                thread.join();  
//            } catch (InterruptedException e) {  
//                throw new RuntimeException(e);  
//            }  
//        }  
        // 加入两个线程  
        threads.forEach(ThreadJoin::join);  
  
        for (int i = 0; i < 5; i++) {  
            System.out.println(Thread.currentThread().getName() + "#" + i);  
        }  
    }  
  
    public static Thread creat(int number) {  
        return new Thread() {  
            @Override  
            public void run() {  
                for (int i = 0; i < 5; i++) {  
                    System.out.println(Thread.currentThread().getName() + "#" + i);  
                }  
            }  
        };  
    }  
  
    public static void join(Thread thread) {  
        try {  
            thread.join();  
        } catch (InterruptedException e) {  
            System.out.println("manba come back");  
        }  
    }  
  
    public static void sleep() {  
        try {  
            Thread.sleep(200);  
        } catch (InterruptedException e) {  
            throw new RuntimeException(e);  
        }  
    }  
}
输出 : 
Thread-0#0
Thread-2#0
Thread-0#1
Thread-2#1
Thread-0#2
Thread-2#2
Thread-0#3
Thread-2#3
Thread-1#0
Thread-0#4
Thread-1#1
Thread-2#4
Thread-1#2
Thread-1#3
Thread-1#4
main#0
main#1
main#2
main#3
main#4

从输出可以看到先执行了两个子线程后再执行了主线程。

3.8.2 join方法结合实战


假设你现在要写一个APP用来帮助顾客查询两个城市之间的航班信息。由于有多家航空公司,所以你得依次查询,然后将结果汇总起来传送给顾客。

package chapter03;  
  
import java.util.ArrayList;  
import java.util.Arrays;  
import java.util.List;  
import java.util.concurrent.ThreadLocalRandom;  
import java.util.concurrent.TimeUnit;  
import java.util.stream.Collector;  
import java.util.stream.Collectors;  
  
interface FightQuery {  
    List<String> get();  
}  
  
class FightQueryTask extends Thread implements FightQuery {  
    private final String origin;  
    private final String destination;  
    private final List<String> flightList = new ArrayList<>();  
  
    public FightQueryTask(String airline, String origin, String destination) {  
        super(airline); // 设置线程名字  
        this.origin = origin;  
        this.destination = destination;  
    }  
  
    @Override  
    public List<String> get() {  
        return flightList;  
    }  
  
    @Override  
    public void run() {  
        System.out.printf("%s-query from %s to %s \n", getName(), origin, destination);  
        int nextInt = ThreadLocalRandom.current().nextInt(10);  
  
        try {  
            TimeUnit.SECONDS.sleep(nextInt);  
            flightList.add(getName() + "-" + nextInt);  
            System.out.printf("The Fight:%s list query successful\n", getName());  
        } catch (InterruptedException e) {  
        }    }  
}  
  
  
public class Test04 {  
    private static final List<String> fightCompany = Arrays.asList("CSA", "CEA", "HNA");  
  
    private static List<String> search(String origin, String destination) {  
        List<String> result = new ArrayList<>();  
        // 创建查询各个航班信息的线程  
        List<FightQueryTask> tasks = fightCompany.stream().  
                map(airline -> creatFightQueryTask(airline, origin, destination)).collect(Collectors.toList());  
        // 启动线程  
        tasks.forEach(Thread::start);  
        // 使用join方法  
        tasks.forEach(Test04::join);  
        // 讲查到的结果全部都加入到结果列表中  
        tasks.stream().map(FightQueryTask::get).forEach(result::addAll);  
        return result;  
    }  
  
    public static FightQueryTask creatFightQueryTask(String airline, String origin, String destination) {  
        return new FightQueryTask(airline, origin, destination);  
    }  
  
    public static void join(Thread thread) {  
        try {  
            thread.join();  
        } catch (InterruptedException e) {  
            throw new RuntimeException(e);  
        }  
    }  
  
    public static void main(String[] args) {  
        List<String> search = search("qiyh", "ihua");  
        search.stream().forEach(System.out::println);  
    }  
}
输出 : 
CSA-query from qiyh to ihua 
HNA-query from qiyh to ihua 
CEA-query from qiyh to ihua 
The Fight:CEA list query successful
The Fight:CSA list query successful
The Fight:HNA list query successful
CSA-3
CEA-2
HNA-4

3.9 如何关闭一个线程


3.9.1 正常关闭


  • 线程结束生命周期正常结束
  • 捕获中断信号关闭线程
    可以通过在线程中捕获中断来退出
package chapter03;  
  
// 温和地退出一个线程  
public class ExitByInterrupt {  
    public static void main(String[] args) throws InterruptedException {  
        Thread thread = new Thread() {  
            @Override  
            public void run() {  
                System.out.println("I will start work");  
                while (!isInterrupted()) {  
                    System.out.println("Working...");  
                    try {  
                        Thread.sleep(5);  
                    } catch (InterruptedException e) {  
                        System.out.println("It's time to play video game...");  
                        interrupt();    // 因为sleep会清除中断信号  
                    }  
                }  
                System.out.println("I'm tired");  
            }  
        };  
        thread.start();  
        Thread.sleep(20);  
        thread.interrupt(); // 中断线程  
    }  
}

在上面的例子中可以通过interrupt方法来终止一个线程。

  • 使用volatile开关控制
package chapter03;  
  
public class Test05 {  
  
    static class MyThread extends Thread {  
        private volatile boolean flag = false;  
  
        @Override  
        public void run() {  
            while (!flag && !isInterrupted()) {  
                System.out.println("Working...");  
                try {  
                    Thread.sleep(5);  
                } catch (InterruptedException e) {  
                    throw new RuntimeException(e);  
                }  
            }  
        }  
  
        public void close() {  
            flag = true;  
        }  
    }  
  
  
    public static void main(String[] args) {  
        MyThread thread = new MyThread();  
        thread.start();  
        try {  
            Thread.sleep(10);  
        } catch (InterruptedException e) {  
            throw new RuntimeException(e);  
        }  
        thread.close();  
    }  
}
输出 : 
Working...
Working...
Working...

3.9.2 异常退出


3.9.3 进程假死


3.10 本章总结


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值