runnable和callable有什么区别
run()和start()有什么区别
线程的状态
线程状态之间的变化
使用join()方法
public class JoinTest {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println("t1");
});
Thread t2 = new Thread(() -> {
try {
// 当t1线程执行完毕后, 线程继续执行
t1.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t2");
});
Thread t3 = new Thread(() -> {
try {
// 当t2线程执行完毕后, 线程继续执行
t2.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("t3");
});
t1.start();
t2.start();
t3.start();
}
}
public class notifyAndNotifyAllTest {
static Object lock = new Object();
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "...waiting...");
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + "...被唤醒了...");
}
}, "t1");
Thread t2 = new Thread(() -> {
synchronized (lock) {
System.out.println(Thread.currentThread().getName() + "...waiting...");
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(Thread.currentThread().getName() + "...被唤醒了...");
}
}, "t2");
t1.start();
t2.start();
Thread.sleep(2000);
synchronized (lock) {
// lock.notify(); // 随机唤醒一个wait线程
lock.notifyAll(); // 唤醒所有wait的线程
}
}
}
不同点
public class InterruptDemo extends Thread{
volatile boolean flag = false; // 线程执行的退出标记
@Override
public void run() {
while(!flag)
{
System.out.println("MyThread...run...");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(String[] args) throws InterruptedException {
// 创建MyThread对象
InterruptDemo t1 = new InterruptDemo();
t1.start();
// 主线程休眠6秒
Thread.sleep(6000);
// 更改标记为true
t1.flag = true;
}
}
public class InterruptDemo02 {
public static void main(String[] args) throws InterruptedException {
// // 1. 打断阻塞的线程
// Thread t1 = new Thread(() -> {
// System.out.println("t1正在运行... ");
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
// }, "t1");
// t1.start();
// Thread.sleep(500);
// t1.interrupt();
// System.out.println(t1.isInterrupted ());
// 2. 打断阻塞的线程
Thread t2 = new Thread(() -> {
while(true)
{
Thread current = Thread. currentThread();
boolean interrupted = current. isInterrupted();
if(interrupted){
System.out.println("打断状态 : "+interrupted);
break;
}
}
}, "t2");
t2.start();
Thread.sleep(500);
t2.interrupt();
System.out.println(t2.isInterrupted());
}
}
黑马程序员. 新版Java面试专题视频教程
小林coding. 图解系统-进程管理
https://gitee.com/Y_cen/java-interview