Synchronized,顾名思义,代表线程同步。那么,在Java编程中如何使用它呢?
我们首先来看这样一个情况:对于同一个变量synDemo,我们分别在2个不同的线程中调用synDemo.synMethord1()与synDemo.synMethord2()。
package com.cnblogs.gpcuster;/** * * @author Aaron.Guo * */
public class Tester {public static void main(String[] args) {final SynDemo synDemo = new SynDemo();Thread thread1 = new Thread() {@Overridepublic void run() {// TODO Auto-generated method stub
super.run();synDemo.synMethord1();}};Thread thread2 = new Thread() {@Overridepublic void run() {// TODO Auto-generated method stub
super.run();synDemo.synMethord2();}};thread1.start();thread2.start();while (true) {try {Thread.sleep(1000);System.out.println("main");} catch (InterruptedException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我们的SynDemo是这样定义的:
package com.cnblogs.gpcuster;/** * * @author Aaron.Guo * */
public class SynDemo{public void synMethord1() {while(true) {try {Thread.sleep(1000);System.out.println("synMethord1");} catch (InterruptedException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void synMethord2() {while(true) {try {Thread.sleep(1000);System.out.println("synMethord2");} catch (InterruptedException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
我们的SynDemo对象没有任何特殊的定义,所以运行起来以后的情况如下:
synMethord2
synMethord1
main
synMethord2
synMethord1
main
synMethord2
synMethord1
接下来,我们给synMethord1添加上synchronized声明,运行情况还是与上次一样,因为我们只有一个线程在调用synMethord1的方法。
我们给synMethord2也添加上synchronized声明,SynDemo对象的代码修改为:
package com.cnblogs.gpcuster;/** * * @author Aaron.Guo * */
public class SynDemo{public synchronized void synMethord1() {while(true) {try {Thread.sleep(1000);System.out.println("synMethord1");} catch (InterruptedException e) {// TODO Auto-generated catch block
e.printStackTrace();
}
}
}