你会用java中synchronized吗--锁定静态实例
1、synchronized使用于一个语句块,锁定一个静态对象的实例,是类级别的锁,同一个对象在这个语句块一次只能由一个线程执行。Talk is cheap.Show me the code.package chapter2;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.util.concurrent.TimeUnit;/*** Created by MyWorld on 2016/3/14.*/public class SynchronizedDemo { public static void main(String[] args) { Business business = new Business(); Worker workerFirst = new Worker(business); Worker workerSecond = new Worker(business); Thread threadFirst = new Thread(workerFirst, "First"); Thread threadSecond = new Thread(workerSecond, "Second"); threadFirst.start(); threadSecond.start(); }}class Worker implements Runnable { private Business business; public Worker(Business business) { this.business = business; } @Override public void run() { try { business.doBusiness(); } catch (InterruptedException e) { e.printStackTrace(); } }}class Business { private static Logger logger = LoggerFactory.getLogger(Business.class); private static final byte[] lock = new byte[0]; public void doBusiness() throws InterruptedException { synchronized (lock) { logger.info("enter synchronized monitor"); TimeUnit.SECONDS.sleep(10); logger.info("leave synchronized monitor"); } }}


3、如果两个Worker对象呢,是不是这样呢?Code:Business business = new Business();Worker workerFirst = new Worker(business);Worker workerSecond = new Worker(business);Thread threadFirst = new Thread(workerFirst, "First");Thread threadSecond = new Thread(workerSecond, "Second");threadFirst.start();threadSecond.start();

5、上面有篇文章有个例子,不是因为使用两个Business实例,就让两个线程由串行改为并行。synchronized锁定对象的实颖蓟段扛例是静态时,是不是也会由串行变为并行呢?Let's have a try!Code:Business businessFirst = new Business();Business businessSecond = new Business();Worker workerFirst = new Worker(businessFirst);Worker workerSecond = new Worker(businessSecond);Thread threadFirst = new Thread(workerFirst, "First");Thread threadSecond = new Thread(workerSecond, "Second");threadFirst.start();threadSecond.start();
