# 并发编程之:Synchronized #
Counter Code
public class Counter { private int count = 0; public int incr() { synchronized (this) { return (++count); } } // 调用次数 private static int reqeust_times; public static synchronized int count() { return ++reqeust_times; } }CounterThread线程
public class CounterThread implements Runnable { //Counter对象 private Counter counter; public CounterThread(Counter counter) { this.counter = counter; } @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + "-----" + counter.incr()); } } }Main方法
public class Main { public static void main(String[] args) { Counter counter = new Counter(); CounterThread counterThread1 = new CounterThread(counter); CounterThread counterThread2 = new CounterThread(counter); new Thread(counterThread1, "线程1").start(); new Thread(counterThread2, "线程2").start(); // 结果是两个线程是同步交替执行incr方法的 // Counter counter1 = new Counter(); // Counter counter2 = new Counter(); // // CounterThread counterThread1 = new CounterThread(counter1); // CounterThread counterThread2 = new CounterThread(counter2); // // new Thread(counterThread1, "线程1").start(); // new Thread(counterThread2, "线程2").start(); // 结果就是各自跑各自的不会互相影响 } } 备注:自己多倒腾一下,颠来倒去的试试就理解了。当然一些原理性的知识点一定要掌握和记住。1、https://www.ibm.com/developerworks/cn/java/j-jtp10264/ 2、http://tutorials.jenkov.com/java-concurrency/synchronized.html 3、https://www.ibm.com/developerworks/cn/java/j-lo-deadlock/