[Effective Java] Synchronous access to shared mutable data
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; //吧对变量的读和写方法都进行同步 private static synchronized void requestStop() { stopRequested = true; } private static synchronized boolean stopRequested() { return stopRequested; } /** * 停止线程变量,这个使用关键字volatile使每个线程都是获取到最新的值 */ 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; } } }); //启动线程 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; } } }); //启动线程 backgroundThread.start(); //停下1s之后执行变量修改程序 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 //这里停不下来是因为主线程对stopRequest进行修改的时候,这个线程并不可见 while(!stopRequested) { ++i; } } }); //启动线程 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

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

