您的位置:首页 > Web前端

【Effective Java】11、同步访问共享的可变数据

2016-10-09 22:01 288 查看
这段时间看的部分感觉没啥需要记录下来的,个人也没什么想法,不过以后还是要多记,多写

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;
}
}


这个main方法是永远不停的,其余两个从两个不同的角度给出了同步的方法

总之:当多个线程共享可变数据的时候,每个读或者写数据的线程都必须执行同步。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: