search
Home类库下载java类库[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.


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)