状态流转图
这里借鉴下狂神说的上课图,例子就是上课的例子
线程方法
join可以想象成插队,相当于VIP一样
停止线程
不推荐使用JDK自带的stop,destory停止线程,已经废弃
推荐
- 线程自己停下来,
- 使用标志位flag,当他为false停止线程
看一下代码
public class ThreadStop implements Runnable{
//设置标志位
private boolean flag=true;
@Override
public void run() {
int i=0;
while (flag){
System.out.println("Thread run"+i);
}
}
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
ThreadStop threadStop=new ThreadStop();
new Thread(threadStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
threadStop.stop();
}
}
}
}
线程休眠
模拟网络延时,放大问题的发生性
模拟倒计时
线程礼让
yield
看个图
public class ThreadTield {
public static void main(String[] args) {
MyYield myYield=new MyYield();
Thread t1=new Thread(myYield,"A");
Thread t2=new Thread(myYield,"B");
t1.start();
t2.start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"开始执行");
Thread.yield();
System.out.println(Thread.currentThread().getName()+"停止执行");
}
}
线程强制执行
join
其实就是插队
public class ThreadJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程VIP来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
ThreadJoin threadJoin=new ThreadJoin();
Thread thread=new Thread(threadJoin);
thread.start();
//主线程
for (int i = 0; i < 500; i++) {
if(i==200){
thread.join();
}
System.out.println("main"+i);
}
}
}
少去使用它,会让线程阻塞
守护线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
例子:
public class ThreadDaemon {
public static void main(String[] args) {
God god =new God();
Thread t1=new Thread(god);
t1.setDaemon(true);
t1.start();
new Thread(new you()).start();
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("上帝守护者你");
}
}
}
class you implements Runnable{
@Override
public void run() {
for (int i = 0; i < 35000; i++) {
System.out.println("你快乐的活着");
}
System.out.println("------去天堂了,byebye");
}
}
线程中断
public class T {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t1.interrupt();
System.out.println(t1.isInterrupted());
}
}