线程同步方法:

(1)、同步代码块,格式: synchronized (同步对象){ //同步代码 }

(2)、同步方法,格式: 在方法前加synchronized修饰 问题: 多个人同时买票。

1、资源没有同步。 package thread; public class Tickets implements Runnable { private int count = 5; @Override public void run() { for (int i = 0; i < 10; ++i) { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } } public static void main(String[] args) { Tickets tickets=new Tickets(); Thread t1=new Thread(tickets); Thread t2=new Thread(tickets); Thread t3=new Thread(tickets); t1.start(); t2.start(); t3.start(); } } 运行结果: 5 3 4 2 2 1 很明显结果是错的。

2、同步代码块 run方法中进行同步,也就是对共享资源(票数、count)进行同步 package thread; public class Tickets implements Runnable { private int count = 5; @Override public void run() { for (int i = 0; i < 10; ++i) { synchronized (this) { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } } } public static void main(String[] args) { Tickets tickets = new Tickets(); Thread t1 = new Thread(tickets); Thread t2 = new Thread(tickets); Thread t3 = new Thread(tickets); t1.start(); t2.start(); t3.start(); } }

3、同步方法 package thread; public class Tickets implements Runnable { private int count = 5; @Override public void run() { for (int i = 0; i < 10; ++i) { sale(); } } public synchronized void sale() { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } public static void main(String[] args) { Tickets tickets = new Tickets(); Thread t1 = new Thread(tickets); Thread t2 = new Thread(tickets); Thread t3 = new Thread(tickets); t1.start(); t2.start(); t3.start(); } }

最新文章

  1. STM32用JLINK 烧写程序时出现NO Cortex-m device found in JTAG chain现象和解决方案
  2. 1.1.1. Atitit Cocos2d-JS v3.x的问题
  3. Jump Game 的三种思路 - leetcode 55. Jump Game
  4. php curl 分离header和body信息
  5. Oracle自定义数据类型 2 (调用对象方法)
  6. 谷歌浏览器-如何让Chrome默认以隐身模式启动?
  7. float和decimal执行效率 (只是代码 没有分析&mdash;)
  8. JDBC小结
  9. [置顶] .net技术类面试、笔试题汇总1
  10. Median of Sorted Arrays
  11. ZigBee研究之旅(二)
  12. MRC、ARC内存管理机制
  13. python爬虫——建立IP池,将可用IP存放到redis
  14. 棋盘 chess
  15. C语言实现邻接矩阵创建无向图&amp;图的深度优先遍历
  16. HTML5 加密和摘要算法(base64,md5, sha1,rsa)
  17. 阿里巴巴 Java开发手册1.4.0
  18. 迅为IMX6核心板兼容工业级、商业扩展级、Plus版本核心板
  19. OCM 学习练习题目
  20. Servlet-转发和重定向的区别

热门文章

  1. leetcode 387
  2. synchronized锁机制的实现原理
  3. iframe onload事件触发两次
  4. C/C++中size_t潜在的问题
  5. Ubuntu国内镜像
  6. 「NOIP2016」蚯蚓
  7. laravel 报错The Mix manifest does not exist.
  8. powershell 无法运行一些脚本的情况
  9. QAction菜单行为
  10. 吴裕雄--天生自然Numpy库学习笔记:NumPy 算术函数