一、synchronized应用的简单示例
下面两段代码示例,分别用同步块,同步方法完成两个线程共同操作的计数器,计数到10。
package concurrency;
public class TwoThreadCounter {
public static volatile boolean goon = false;
public static int nums = 0;
public static void main(String[] args) {
Thread counter1 = new Thread(new Runnable() {
@Override
public void run() {
while(goon){
synchronized (TwoThreadCounter.class) {
nums++;
System.out.println(Thread.currentThread().getName() + "\t" + nums);
if(nums == 10) {
goon = false;
TwoThreadCounter.class.notifyAll();
}else{
try {
TwoThreadCounter.class.notifyAll();
TwoThreadCounter.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}, "counter1");
Thread counter2 = new Thread(new Runnable() {
@Override
public void run() {
while(goon) {
synchronized (TwoThreadCounter.class) {
nums++;
System.out.println(Thread.currentThread().getName() + "\t" + nums);