1. 程式人生 > >多線程基礎二(線程的啟動、終止,線程面臨的三種問題)

多線程基礎二(線程的啟動、終止,線程面臨的三種問題)

主線程 影響 stop pub atom out 通過 println 性問題

一、線程的啟動、終止方式

 啟動: 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規範了上述線程的三個問題

多線程基礎二(線程的啟動、終止,線程面臨的三種問題)