验证同步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

猜你喜欢

转载自blog.csdn.net/qq_20610631/article/details/81490296
今日推荐