Home  >  Article  >  类库下载  >  [Effective Java] Synchronous access to shared mutable data

[Effective Java] Synchronous access to shared mutable data

高洛峰
高洛峰Original
2016-10-10 08:57:131621browse

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