synchronsized修饰方法的使用
2016-05-29 13:41
363 查看
线程同步是指对共享资源,若不是共享资源则不涉及线程同步问题。
synchronized方法可以锁定对象,也可以锁定代码块。
当锁定对象时,修饰在类的方法前面。记住:若两个线程同时访问一个对象的不同方法,且对象有一个synchronized方法和一个非synchronized方法,则是两个线程并不涉及同步问题。只有当访问同一个对象的synchronsized方法(可以是不同的synchronized方法)时才会有同步。
比如对象toy有如下两个方法
synchronized方法可以锁定对象,也可以锁定代码块。
当锁定对象时,修饰在类的方法前面。记住:若两个线程同时访问一个对象的不同方法,且对象有一个synchronized方法和一个非synchronized方法,则是两个线程并不涉及同步问题。只有当访问同一个对象的synchronsized方法(可以是不同的synchronized方法)时才会有同步。
比如对象toy有如下两个方法
package concurrent1; public class toy { private int number; public toy(){ number = 100; } synchronized public void paint() { System.out.println("thread:"+Thread.currentThread().getName() + ":paint begin"); try{ int i = (int) (Math.random()*1000); Thread.sleep(i); } catch(Exception e) { } System.out.println("thread:"+Thread.currentThread().getName()+":paint"); System.out.println("thread:"+Thread.currentThread().getName() + ":paint end"); } synchronized public void write() { System.out.println("thread:"+Thread.currentThread().getName() + ":write begin"); try{ int i = (int) (Math.random()*1000); Thread.sleep(i); } catch(Exception e) { } System.out.println("thread:"+Thread.currentThread().getName()+":write"); System.out.println("thread:"+Thread.currentThread().getName() + ":write end"); } }
package concurrent1; public class Test { public static void main(String[] args) { // TODO Auto-generated method stub toy mytoy = new toy(); boy myboy = new boy(mytoy); boy youboy = new boy(mytoy); myboy.setName("myboy"); youboy.setName("youboy"); myboy.start(); youboy.start(); } }结果:
thread:myboy:write begin thread:myboy:write thread:myboy:write end thread:myboy:paint begin thread:myboy:paint thread:myboy:paint end thread:youboy:write begin thread:youboy:write thread:youboy:write end thread:youboy:paint begin thread:youboy:paint thread:youboy:paint end若将paint方法前的synchronized取消掉,输出如下,可以看出write方法是异步执行的,只有paint方法是同步执行的。
thread:myboy:write begin thread:youboy:write begin thread:myboy:write thread:myboy:write end thread:myboy:paint begin thread:myboy:paint thread:myboy:paint end thread:youboy:write thread:youboy:write end thread:youboy:paint begin thread:youboy:paint thread:youboy:paint end
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序
- 二叉查找树