JAVA synchronized 同步锁 简析

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_加法_1475985582
Thread-2_加法_1475985583
Thread-2_加法_1475985584
Thread-2_加法_1475985585
Thread-3_除法_1475985586
Thread-3_除法_1475985587
Thread-3_除法_1475985588
Thread-3_除法_1475985589
Thread-3_除法_1475985590
Thread-3_除法_1475985591
Thread-2_加法_1475985592
Thread-2_加法_1475985593
Thread-2_加法_1475985594
Thread-2_加法_1475985595
Thread-2_加法_1475985596
Thread-3_除法_1475985597
Thread-2_加法_1475985598
Thread-3_除法_1475985599
Thread-3_除法_1475985600
Thread-3_除法_1475985601

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值