线程同步是指对共享资源,若不是共享资源则不涉及线程同步问题。
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
时间: 2024-10-28 21:54:57