同步代码块的使用

package com.freeflying.thread.sync;
/**
 * 同步代码块的使用
 * @ClassName: SyncCodeBlock  
 * @Description:
 * @author freeflying
 * @date 2018年7月2日
 */
public class SyncCodeBlock {
	public static void main(String[] args) {
		SyncCodeBlockEx syncCodeBlockEx=new SyncCodeBlockEx();
		SyncCodeBlockThreadA syncCodeBlockThreadA=new SyncCodeBlockThreadA(syncCodeBlockEx);
		syncCodeBlockThreadA.setName("thread a");
		syncCodeBlockThreadA.start();
		SyncCodeBlockThreadB syncCodeBlockThreadB=new SyncCodeBlockThreadB(syncCodeBlockEx);
		syncCodeBlockThreadB.setName("thread B");
		syncCodeBlockThreadB.start();
	}
}
class SyncCodeBlockEx{
	public void method() {
		try {
			synchronized(this) {
				System.out.println("beign time:"+System.currentTimeMillis());
				Thread.sleep(2000);
				System.out.println("end time:"+System.currentTimeMillis());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
class SyncCodeBlockThreadA extends Thread{
	private SyncCodeBlockEx syncCodeBlockEx;
	public SyncCodeBlockThreadA(SyncCodeBlockEx syncCodeBlockEx) {
		this.syncCodeBlockEx=syncCodeBlockEx;
	}
	@Override
	public void run() {
		syncCodeBlockEx.method();
	}
}
class SyncCodeBlockThreadB extends Thread{
	private SyncCodeBlockEx syncCodeBlockEx;
	public SyncCodeBlockThreadB(SyncCodeBlockEx syncCodeBlockEx) {
		this.syncCodeBlockEx=syncCodeBlockEx;
	}
	@Override
	public void run() {
		syncCodeBlockEx.method();
	}
}

结果:

beign time:1530537312138
end time:1530537314139
beign time:1530537314139
end time:1530537316139
当两个线程并发访问同一个对象时中的同步代码块时,一段时间内只能有一个线程能被执行,另一个线程只能等待当前线程执行完这个代码块以后才能执行该代码块

你可能感兴趣的:(java多线程)