synchronized同步机制的应用
2016-06-28 21:57
295 查看
public class TextThread { /** * 该程序是为了说明synchronized锁住对象的条件, * 即同步的两个或多个线程必须是对同一对象上锁 * (不管是this表示的当前对象,还是其他定义的 * 对象如String对象等) * 如果每个线程新建不同的对象,然后对不同对象上锁 * 如TxtThread tt0 = new TxtThread();TxtThread tt1 = new TxtThread(); * 然后对当前对象this上锁,将会失效。 */ public static void main(String[] args) { // TODO 自动生成方法存根 TxtThread tt0 = new TxtThread(); // TxtThread tt1 = new TxtThread(); // TxtThread tt2 = new TxtThread(); // TxtThread tt3 = new TxtThread(); tt0.flag = false; new Thread(tt0).start(); TxtThread tt1 = new TxtThread(); //tt1.flag = true; new Thread(tt0).start(); // new Thread(tt0).start(); // new Thread(tt0).start(); // new Thread(tt1).start(); // new Thread(tt2).start(); // new Thread(tt3).start(); } } class TxtThread implements Runnable { static String str = new String(); boolean flag; public void run() { if (flag == true) { for (int i = 1; i <= 20; i++) { try { Thread.sleep(10); } catch (Exception e) { e.getMessage(); } System.out.println("鎖之外"); } synchronized (this) { int num = 100; while (num > 0) { try { Thread.sleep(10); } catch (Ex aba2 ception e) { e.getMessage(); } System.out.println(Thread.currentThread().getName() + "this is 模块1 " + num--); } } } if (flag == false) { synchronized (this) { int num = 100; while (num > 0) { try { Thread.sleep(10); } catch (Exception e) { e.getMessage(); } System.out.println(Thread.currentThread().getName() + "this is模块2 " + num--); } } } } }
相关文章推荐
- Android 开发之旅——Android Studio2 安装 GO!
- GAP LOCK(间隙锁)
- php 写session
- php 写session
- php 写session
- Linux环境下完成远程系统迁移
- STK和Matlab编程规范
- 深圳为什么青睐无人机?
- HIVE配置文件
- MySql-InnoDB存储引擎的锁和事务
- VUX 移动前端框架使用文档
- redis缓存mysql
- 写博客的一点小心得
- 数据库 PLSQL 创建表格
- 利用docker开启持续交付之路
- HDOJ 4342 History repeat itself
- 自绘Tab控件
- C#中Dictionary<TKey,TValue>排序方式
- koa学习2——koa入门
- session入mysql