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