JAVA synchronized 同步锁 简析

来源:互联网 发布:淘宝交易关闭怎么恢复 编辑:程序博客网 时间:2024/06/05 05:59
package proj_decode;public class TestSynchornized {public static synchronized void add() {//类锁long time = System.currentTimeMillis() / 1000;System.out.println(Thread.currentThread().getName() + "_加法_" + time);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}public void devision() {synchronized (TestSynchornized.class) {//类锁long time = System.currentTimeMillis() / 1000;System.out.println(Thread.currentThread().getName() + "_除法_" + time);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}public void plus() {synchronized (TestSynchornized.this) {//对象锁long time = System.currentTimeMillis() / 1000;System.out.println(Thread.currentThread().getName() + "_减法_" + time);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}public synchronized void multiplication() {//对象锁long time = System.currentTimeMillis() / 1000;System.out.println(Thread.currentThread().getName() + "_乘法_" + time);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args) {final TestSynchornized t = new TestSynchornized();Thread a1 = new Thread() {public void run() {for (int i = 0; i < 10; i++) {t.plus();}}};Thread a2 = new Thread() {public void run() {for (int i = 0; i < 10; i++) {t.multiplication();}}};Thread a3 = new Thread() {public void run() {for (int i = 0; i < 10; i++) {TestSynchornized.add();}}};Thread a4 = new Thread() {public void run() {for (int i = 0; i < 10; i++) {t.devision();}}};//a1.start();//a2.start();a3.start();a4.start();}}
结果:
Thread-2_加法_1475985582Thread-2_加法_1475985583Thread-2_加法_1475985584Thread-2_加法_1475985585Thread-3_除法_1475985586Thread-3_除法_1475985587Thread-3_除法_1475985588Thread-3_除法_1475985589Thread-3_除法_1475985590Thread-3_除法_1475985591Thread-2_加法_1475985592Thread-2_加法_1475985593Thread-2_加法_1475985594Thread-2_加法_1475985595Thread-2_加法_1475985596Thread-3_除法_1475985597Thread-2_加法_1475985598Thread-3_除法_1475985599Thread-3_除法_1475985600Thread-3_除法_1475985601

0 0