同步方法的几种常见写法
2015-12-10 11:11
295 查看
同步的位置分三种:(1)静态方法的同步,(2)非静态方法的同步,(3)代码块的同步
静态方法的同步:
非静态方法的同步
代码块的同步:(1)
同步代码块(3)
静态方法的同步:
public static synchronized void check(){ int i =0; while(i>100){ try { System.err.println("栈满了"); SynchronizedStack.class.wait();// 等待,直到有数据出栈 } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } i++; System.out.println("正在使用第"+i+"个"); }
非静态方法的同步
public synchronized char pop() { while (index == 0) { try { System.err.println("栈空了"); this.wait();// 等待,直到有数据出栈 } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } index--; // 指针向下移动 char ch = data[index]; this.notify(); // 通知其它线程把数据入栈 return ch; }
代码块的同步:(1)
public void check1(int i){ synchronized(this){ while(i>100){ try { System.err.println("栈满了"); SynchronizedStack.class.wait();// 等待,直到有数据出栈 } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } i++; System.out.println("正在使用第"+i+"个"); SynchronizedStack.class.notify(); } }
同步代码块:(2)
</pre><pre name="code" class="java">public void check2(int i){ synchronized(SynchronizedStack.class){ while(i>100){ try { System.err.println("栈满了"); SynchronizedStack.class.wait();// 等待,直到有数据出栈 } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } i++; System.out.println("正在使用第"+i+"个"); SynchronizedStack.class.notify(); } }
同步代码块(3)
public static void check2(int i){ synchronized(SynchronizedStack.class){ while(i>100){ try { System.err.println("栈满了"); SynchronizedStack.class.wait();// 等待,直到有数据出栈 } catch (InterruptedException e) { Thread.currentThread().interrupt(); e.printStackTrace(); } } i++; System.out.println("正在使用第"+i+"个"); SynchronizedStack.class.notify(); } }
相关文章推荐
- LVS实现负载均衡
- effective c++ 学习笔记 1
- NSURL 的简单使用
- maven pom.xml文件第一行报错,用以下设置即可
- 【springmvc+mybatis项目实战】杰信商贸-6.重点知识回顾
- hadoop安装,单机,伪分布
- OnCreateClient
- 【springmvc+mybatis项目实战】杰信商贸-7.生产厂家新增
- iOS UI NavigationController UINavigationBar UINavigationItem
- 【springmvc+mybatis项目实战】杰信商贸-8.生产厂家修改
- Pycharm5注册方式
- 浏览器对象模型BOM
- 指针
- discuz密码错误15分钟后重新登录
- python基础教程共60课-第21课函数的参数
- Actions and Attributes from Wholes and Parts
- 如何理解Cookie的接收与响应?
- php 调试 core dump
- Tomcat服务器与HTTP协议
- 2014年总结