使用Runnable实现数据共享
使用Runnable实现数据共享,供大家参考,具体内容如下
先上代码:
public class TestThread { private static final Logger logger = LoggerFactory.getLogger(TestThread.class); private final class MyRunnable implements Runnable { private int i; public MyRunnable() { this.i = 10; } public void run() { while(i > 0) { synchronized (this) { if (i > 0) { i--; logger.debug("{} buy one ticket, {} left. ", Thread.currentThread().getName(), i); } } } } } @Test public void testRunable() throws InterruptedException{ MyRunnable myRunnable = new MyRunnable(); Thread th1 = new Thread(myRunnable); Thread th2 = new Thread(myRunnable); th1.start(); th2.start(); th1.join(); th2.join(); } }
楼上的代码很简单,模拟一个售票系统。通过两个Thread对象开启两条线程同时运行一个MyRunnable实例。
几个注意点:
1. 没有加上synchronised关键词的话,即
public void run() { while(i > 0) { if (i > 0) { i--; logger.debug("{} buy one ticket, {} left. ", Thread.currentThread().getName(), i); } } }
系统的运行结果:
Thread-1 buy one ticket, 8 left. Thread-2 buy one ticket, 8 left. Thread-2 buy one ticket, 6 left. Thread-1 buy one ticket, 6 left. Thread-2 buy one ticket, 5 left. Thread-1 buy one ticket, 4 left. Thread-2 buy one ticket, 3 left. Thread-1 buy one ticket, 2 left. Thread-2 buy one ticket, 1 left. Thread-1 buy one ticket, 0 left.
可以看到,缺少同步的程序输出明显有问题。
2. 在进入同步代码块之后,还需要对i的值再进行一次判断,即,如果不加if判断:
public void run() { while(i > 0) { synchronized (this) { i--; logger.debug("{} buy one ticket, {} left. ", Thread.currentThread().getName(), i); } } }
程序的运行结果为:
Thread-2 buy one ticket, 9 left. Thread-2 buy one ticket, 8 left. Thread-2 buy one ticket, 7 left. Thread-2 buy one ticket, 6 left. Thread-2 buy one ticket, 5 left. Thread-2 buy one ticket, 4 left. Thread-2 buy one ticket, 3 left. Thread-2 buy one ticket, 2 left. Thread-2 buy one ticket, 1 left. Thread-2 buy one ticket, 0 left. Thread-1 buy one ticket, -1 left.
可以看出,出现了“多卖”的现象, 所以需要在进入同步代码块中再进行一次if判断。
总结
synchronised用于互斥访问共享变量, 并在同步代码块中使用if判断更新共享变量。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
interrupt()和线程终止方式_动力节点Java学院整理
线程的thread.interrupt()方法是中断线程,将会设置该线程的中断状态位,即设置为true,中断的结果线程是死亡、还是等待新的任务或是继续运行至下一步,就取决于这个程序本身2017-05-05详谈Java编程之委托代理回调、内部类以及匿名内部类回调(闭包回调)
下面小编就为大家带来一篇详谈Java编程之委托代理回调、内部类以及匿名内部类回调(闭包回调)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-05-05SpringBoot@DeleteMapping(/xxx/{id})请求报405的解决
这篇文章主要介绍了SpringBoot@DeleteMapping(/xxx/{id})请求报405的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2023-01-01SpringBoot项目获取统一前缀配置及获取非确定名称配置方法
在SpringBoot项目中,使用@ConfigurationProperties注解可获取统一前缀的配置,具体做法是创建配置类,使用prefix属性指定配置的前缀,本文给大家介绍SpringBoot项目获取统一前缀配置以及获取非确定名称配置方法,感兴趣的朋友跟随小编一起看看吧2024-09-09
最新评论