接上篇,本篇演示锁加在类上面
public class T {private static Integer count = 0;public static void m() {//任何线程要执行下面的代码,必须先拿到当前对象的锁//锁的是当前对象synchronized (T.class) {for (int i = 0; i < 100000; i++) {count++;}}}public static void main(String[] args) throws InterruptedException {// 采用 CountDownLatch 保证了所有线程同时开始,同时结束CountDownLatch start = new CountDownLatch(1);CountDownLatch end = new CountDownLatch(10);T t = new T();for (int i = 0; i < 10; i++) {new Thread(() -> {try {start.await();m();} catch (InterruptedException e) {e.printStackTrace();} finally {end.countDown();}}).start();}start.countDown();end.await();System.out.println(Thread.currentThread().getName() + " count = " + count);}}输出结果:main count = 1000000
public class T {private static Integer count = 0;public synchronized static void m() {//任何线程要执行下面的代码,必须先拿到当前对象的锁//锁的是当前对象for (int i = 0; i < 100000; i++) {count++;}}public static void main(String[] args) throws InterruptedException {// 采用 CountDownLatch 保证了所有线程同时开始,同时结束CountDownLatch start = new CountDownLatch(1);CountDownLatch end = new CountDownLatch(10);T t = new T();for (int i = 0; i < 10; i++) {new Thread(() -> {try {start.await();m();} catch (InterruptedException e) {e.printStackTrace();} finally {end.countDown();}}).start();}start.countDown();end.await();System.out.println(Thread.currentThread().getName() + " count = " + count);}}main count = 1000000
如果要锁对象必须是静态的
public class T {private static Integer count = 0;static Object o = new Object();public static void m() {//任何线程要执行下面的代码,必须先拿到当前对象的锁//锁的是当前对象synchronized (o) {for (int i = 0; i < 100000; i++) {count++;}}}public static void main(String[] args) throws InterruptedException {// 采用 CountDownLatch 保证了所有线程同时开始,同时结束CountDownLatch start = new CountDownLatch(1);CountDownLatch end = new CountDownLatch(10);T t = new T();for (int i = 0; i < 10; i++) {new Thread(() -> {try {start.await();m();} catch (InterruptedException e) {e.printStackTrace();} finally {end.countDown();}}).start();}start.countDown();end.await();System.out.println(Thread.currentThread().getName() + " count = " + count);}}main count = 1000000
错误例子,不可以直接锁this
public class T {private static Integer count = 0;public static void m() {//任何线程要执行下面的代码,必须先拿到当前对象的锁//锁的是当前对象synchronized (this) {// 此处编译报错for (int i = 0; i < 100000; i++) {count++;}}}public static void main(String[] args) throws InterruptedException {// 采用 CountDownLatch 保证了所有线程同时开始,同时结束CountDownLatch start = new CountDownLatch(1);CountDownLatch end = new CountDownLatch(10);T t = new T();for (int i = 0; i < 10; i++) {new Thread(() -> {try {start.await();m();} catch (InterruptedException e) {e.printStackTrace();} finally {end.countDown();}}).start();}start.countDown();end.await();System.out.println(Thread.currentThread().getName() + " count = " + count);}}
