一、线程的启动、终止方式

  启动: start native(调用外部接口启动)

    终止:    stop(类似kill,暴力终止)  interrupt 中断的方式 通过指令的方式 volatile boolean stop = false;

public class InterruptDemo {

private static int i;
public static void main(String[] args) {
Thread thread = new Thread(()->{
while(!Thread.currentThread().isInterrupted()){//判断是否有interrupt标识
i++;
}
System.out.println(i);
},"interrupt");
thread.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.interrupt();//设置interrupt标识为true
System.out.println(Thread.interrupted());
}
}

二、线程的面临的三大问题
  
(1)可见性问题
  
private volatile static boolean stop = false;可见性
//private static boolean stop = false;
//main主线程
public static void main(String[] args) throws InterruptedException {
//thread子线程
Thread thread = new Thread(()->{
int i = 0;
while (!stop){
i++;
}
System.out.println(i);
});
thread.start();
TimeUnit.SECONDS.sleep(1);
stop = true;//主线程改变值,子线程不可见,加上volatile后子线程可见
}

(2)原子性问题
    
private static int count = 0;

public static void inc(){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}
public static void main(String[] args) throws InterruptedException {

for (int i=0 ; i<1000;i++){
new Thread(AtomicDemo::inc).start();
}
Thread.sleep(4000);
System.out.println("运行结果:"+count);
}

运行结果却不一定能够是1000,之间相互影响

(3)有序性问题
根据编译,缓存的一致性问题等因素,程序的执行可能不会按照所编写的执行。

JMM规范了上述线程的三个问题

Copyright © 2024 FLGB
Powered by .NET 8.0 on Kubernetes