验证同步synchronized(this) 代码块是锁定当前对象的(synchronized 方法一样, synchronized(this) 也是锁定当前对象的)

与synchronized 方法一样, synchronized(this) 也是锁定当前对象的

package mytask;
public class Task {
	synchronized public void otherMethod() {
		System.out.println("------------------------run--otherMethod");
	}
	public void doLongTimeTask() {
		synchronized (this) {
			for (int i = 0; i < 10000; i++) {
				System.out.println("synchronized threadName="
						+ Thread.currentThread().getName() + " i=" + (i + 1));
			}
		}
	}
}
package mythread;
import mytask.Task;
public class MyThread1 extends Thread {
	private Task task;
	public MyThread1(Task task) {
		super();
		this.task = task;
	}
	@Override
	public void run() {
		super.run();
		task.doLongTimeTask();
	}
}
package mythread;
import mytask.Task;
public class MyThread2 extends Thread {
	private Task task;
	public MyThread2(Task task) {
		super();
		this.task = task;
	}
	@Override
	public void run() {
		super.run();
		task.otherMethod();
	}
}
package test;
import mytask.Task;
import mythread.MyThread1;
import mythread.MyThread2;
public class Run {
	public static void main(String[] args) throws InterruptedException {
		Task task = new Task();
		MyThread1 thread1 = new MyThread1(task);
		thread1.start();
		Thread.sleep(100);
		MyThread2 thread2 = new MyThread2(task);
		thread2.start();
	}
}

结果

synchronized threadName=Thread-0 i=1
synchronized threadName=Thread-0 i=2
synchronized threadName=Thread-0 i=3
synchronized threadName=Thread-0 i=4
synchronized threadName=Thread-0 i=5
synchronized threadName=Thread-0 i=6
synchronized threadName=Thread-0 i=7
synchronized threadName=Thread-0 i=8
synchronized threadName=Thread-0 i=9
synchronized threadName=Thread-0 i=10
Thread-1run--otherMethod

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值