Thread.join()
public class MyJoinTest {
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thread(()-> System.out.println("Thread0"));
Thread t1 = new Thread(new Thread1(), "myThread1");
Thread t2 = new Thread(new Thread2(), "myThread2");
t2.start();
t2.join();
t0.start();
t0.join();
t1.start();
t1.join();
// 会使主线程处于一个阻塞状态 保持当前线程对其他线程的可见性
// 能够使主线程阻塞的方式:本质是native方法 waite notify 实现的
// 线程的调度算法: OS当中,CPU竞争的有很多策略。Unix系统使用的是时间片算法,但是Windows属于抢占式
// 时间片算法 线程任务会排成一个队 每个拥有一定的时间片 依次执行
// 对于sleep(0)的意义?触发操作系统线程的重新开始竞争
// Thread.sleep(1000);
System.out.println("myMain");
}
static class Thread1 implements Runnable {
@Override
public void run() {
System.out.println("Thread1");
}
}
static class Thread2 implements Runnable{
@Override
public void run() {
System.out.println("Thread2");
}
}
}
// print reuslt
Thread2
Thread0
Thread1
myMain
join 底层使用wait 和 notify实现的
t.join()方法只会使主线程(或者说调用t.join()的线程)进入等待池并等待t线程执行完毕后才会被唤醒。并不影响同一时刻处在运行状态的其他线程所以使用join 能够保证线程的一定的 运行顺序,上述demo顺序一直不会改变
之前对于join()方法只是了解它能够使得t.join()中的t优先执行,当t执行完后才会执行其他线程。能够使得线程之间的并行执行变成串行执行下面分析一下join的源码!
// 实例方法thread.sleep()
public final void join() throws InterruptedException {
join(0); // thread.join()=thread.join(0)
}
// 可见join是一个同步方法,调用Object.wait()实现的
public final synchronized void join(long millis)
throws InterruptedException {
long base = System.currentTimeMillis();
long now = 0;
if (millis < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (millis == 0) {
while (isAlive()) {
wait(0);// 这个wait(0)意思是直到被notify 会一直阻塞下去
}
} else {
while (isAlive()) {
long delay = millis - now;
if (delay <= 0) {
break;
}
wait(delay);
now = System.currentTimeMillis() - base;
}
}
}
join源码中,只会调用wait方法,并没有在结束时调用notify,这是因为线程在die的时候会自动调用自身的notifyAll方法,来释放所有的资源和锁
线程结束:run方法执行完毕
Thread.sleep()
是线程执行过程当中暂停一会儿,直到等待时间恢复执行或者在等待过程当中被中断
Thread.sleep()的执行过程:
- 挂起线程并修改其运行状态,使用sleep提供的参数设置一个定时器
- 当时间结束,定时器会触发,内核收到中断后修改其运行状态,线程会被标志就绪进入就绪队列等待系统调度
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of {@code millis} is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public static native void sleep(long millis) throws InterruptedException;
wait() & notify()
可进行线程间的通信:生产者 消费者模型
public class Producer implements Runnable {
private Queue<String> bags;
private int size;
public Producer(Queue<String> bags, int size) {
this.bags = bags;
this.size = size;
}
@Override
public void run() {
int i = 0;
while (true) {
i++;
synchronized (bags) {
while (bags.size() == size) {
System.out.println("bags已经满了!" + size);
try {
bags.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bags.add("bag" + i);
System.out.println("生产者生产了bag" + i);
bags.notifyAll();
}
}
}
}
// 省去消费者代码 跟生产者差不多
public class ProduceAndCustomerTest {
public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
int size = 10;
new Thread(new Customer(queue, size)).start();
new Thread(new Producer(queue, size)).start();
// 为什么waite & notify 需要加synchronized?
// 本质上是一种竞争 加上对象锁进行竞争 来实现线程间的通信 线程的阻塞和唤醒
}
}
interrupt & interrupted
public class InterruptionExceptionDemo {
private static int i = 0;
private static volatile boolean flag = false;
/**
* @Description: 当run方法执行完,该线程就结束了
*/
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thread(() -> {
while (!flag) {
i++;
System.out.println(i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t0.start();
TimeUnit.SECONDS.sleep(2);
// 基于这个共享变量 实现线程间的通信
// to.stop() 相当于kill -9 存在安全隐患
flag = true;
}
}
// print result
1
2
3
4
除此之外 有没有比较有很好的方式结束线程呢? 就是我们的interrupt and interrupted
/**
* @Class InterruptionExceptionDemo1
* @Description: 线程阻塞的状态有三种方式
* thread.join() Thread.sleep() Object.wait()
* 中断之后,先抛出interrupted异常,然后唤醒线程
*/
public class InterruptionExceptionDemo1 {
private static int i = 0;
public static void main(String[] args) throws InterruptedException {
Thread t0 = new Thread(()-> {
//默认isInterrupted is false used interrupt() later
//to be true-->last we used interrupted()-->to be false and thread will be
//阻塞
while(!Thread.currentThread().isInterrupted()){
//System.out.println("before interrupt-->" + Thread.currentThread().isInterrupted());
try {
TimeUnit.SECONDS.sleep(4);
i++;
System.out.println(i);
System.out.println(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t0.start();
Thread.sleep(2000);
t0.interrupt();//-->InterruptedException
long before = System.currentTimeMillis();
System.out.println(before);
//t0.isInterrupted();
//t0.stop();相当于kill -9,存在很多不安全的情况
}
}
在当前线程阻塞的情况下,当其他线程调用当前线程的thread.interrupt(), 表示向当前线程打个招呼说你可以继续执行了;
然后当前线程会抛出一个interrupted异常,然后当前线程被唤醒
// 了解一下Thread.interrupted()
public class InterruptionExceptionDemo2 {
private static volatile boolean flag = true;
public static void main(String[] args) throws InterruptedException {
Thread t2 = new Thread(()-> {
while(flag){
if (Thread.currentThread().isInterrupted()){
System.out.println("<?>" + System.currentTimeMillis());
System.out.println("before interrupt-->" + Thread.currentThread().isInterrupted());
Thread.interrupted();
System.out.println("after interrupt-->" + Thread.currentThread().isInterrupted());
if (!Thread.currentThread().isInterrupted()){
flag = false;
System.out.println("结束线程!");
}
}
}
});
t2.start();
t2.interrupt();//-->InterruptedException
Thread.sleep(1000);
System.out.println("^_^" + System.currentTimeMillis());
}
}
Thread.interrupted():对中断标识进行复位
通俗的说就是 回到原来阻塞的状态