I feel like there is nothing that needs to be recorded during this period of time, and I personally don’t have any ideas, but I will still have to remember and write more in the future
package cn.xf.cp.ch02.item66; import java.util.concurrent.TimeUnit; import org.junit.Test; public class StopThread { /** * 停止線程變量 */ private static boolean stopRequested; //吧對(duì)變量的讀和寫方法都進(jìn)行同步 private static synchronized void requestStop() { stopRequested = true; } private static synchronized boolean stopRequested() { return stopRequested; } /** * 停止線程變量,這個(gè)使用關(guān)鍵字volatile使每個(gè)線程都是獲取到最新的值 */ private static volatile boolean stopRequested2; @Test public void test() { Thread backgroundThread = new Thread(new Runnable() { @Override public void run() { int i = 0; while(!stopRequested()) { ++i; } } }); //啟動(dòng)線程 backgroundThread.start(); //休眠1秒 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } requestStop(); } @Test public void test2() { Thread backgroundThread = new Thread(new Runnable() { @Override public void run() { int i = 0; System.out.println("這里使用最新的stopRequested2值"); while(!stopRequested2) { ++i; } } }); //啟動(dòng)線程 backgroundThread.start(); //停下1s之后執(zhí)行變量修改程序 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } //修改變量 stopRequested2 = true; } public static void main(String[] args) throws InterruptedException { Thread backgroundThread = new Thread(new Runnable() { @Override public void run() { int i = 0; System.out.println(stopRequested); //false //這里停不下來(lái)是因?yàn)橹骶€程對(duì)stopRequest進(jìn)行修改的時(shí)候,這個(gè)線程并不可見(jiàn) while(!stopRequested) { ++i; } } }); //啟動(dòng)線程 backgroundThread.start(); //休眠1秒 TimeUnit.SECONDS.sleep(1); stopRequested = true; } }
This main method will never stop, and the other two are from two different angles Synchronization methods are given
In short: when multiple threads share variable data, each thread that reads or writes data must perform synchronization.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)