Java synchronized 关键字是将锁放在对象上的,因此同一个类不同对象,那么是不受影响的。写两个小程序来测试一下。
先记录下同一个对象的情况:
package com.lenovo.plm.dms.p4; public class Service { private long record; public Service(long record){ this.record = record; } synchronized public void addRecord(){ System.out.println(Thread.currentThread().getName() + ":"+ record++); } }
package com.lenovo.plm.dms.p4; public class MyThread extends Thread{ private Service service; public MyThread(Service service){ this.service = service; } @Override public void run() { // TODO Auto-generated method stub super.run(); for(int i = 0;i<1000;i++){ service.addRecord(); } } }
package com.lenovo.plm.dms.p4; public class Main { public static void main(String[] args) { Service service = new Service(0); MyThread t1 = new MyThread(service); t1.start(); MyThread t2 = new MyThread(service); t2.start(); } }
Thread-0:1319
Thread-0:1320
Thread-0:1321
Thread-0:1322
Thread-0:1323
Thread-0:1324
Thread-0:1325
Thread-0:1326
Thread-0:1327
Thread-0:1328
Thread-1:1329
Thread-1:1330
Thread-1:1331
Thread-1:1332
Thread-1:1333
Thread-1:1334
Thread-1:1335
Thread-1:1336
Thread-1:1337
Thread-1:1338
Thread-1:1339
Thread-1:1340
可以看出两个线程是同步的。
再记录一种情况,就是两个线程操作同一个类的两个对象。
Service 类定义相同。
线程类定义如下:
package com.lenovo.plm.dms.p5; public class MyThread extends Thread { @Override public void run() { // TODO Auto-generated method stub super.run(); Service service = new Service(0); for(int i = 0;i<1000;i++){ service.addRecord(); } } }
执行类定义如下:
package com.lenovo.plm.dms.p5; public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); MyThread t2 = new MyThread(); t2.start(); } }
Thread-1:995
Thread-1:996
Thread-1:997
Thread-1:998
Thread-1:999
Thread-0:972
Thread-0:973
Thread-0:974
Thread-0:975
Thread-0:976
Thread-0:977
Thread-0:978
Thread-0:979
Thread-0:980
Thread-0:981
Thread-0:982
Thread-0:983
Thread-0:984
Thread-0:985
Thread-0:986
Thread-0:987
Thread-0:988
Thread-0:989
Thread-0:990
Thread-0:991
Thread-0:992
Thread-0:993
Thread-0:994
Thread-0:995
Thread-0:996
Thread-0:997
Thread-0:998
Thread-0:999
可以看出两个线程的计算结果是独立的,互相不影响。