您的位置:首页 > 编程语言 > Java开发

synchronsized修饰方法的使用

2016-05-29 13:41 363 查看
线程同步是指对共享资源,若不是共享资源则不涉及线程同步问题。

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息