在Java代码中经常见到synchronized这个关键字。
许多老鸟也经常使用synchronized。但是,你确定知道synchronized怎么用吗?
本文简要介绍一下synchronized的用法之修饰静态方法
前期准备工作(包括相关工具或所使用的原料等)javasynchronizedThread 详细的操作方法或具体步骤
synchronized修饰的静态方法,是类级别的锁,一次只能由一个线程执行。
Talk is cheap.Show me the code.
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 worker=new Worker(business);
Thread threadFirst=new Thread(worker, "First");
Thread threadSecond=new Thread(worker, "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);
public static synchronized void doBusiness() throws InterruptedException {
logger.info("enter synchronized monitor");
TimeUnit.SECONDS.sleep(10);
logger.info("leave synchronized monitor");
}
}



执行上面的代码,看看两个线程是不是串行执行的呢?是的
Output:
2016-03-14 23:17:44,785 [First] INFO - enter synchronized monitor
2016-03-14 23:17:54,787 [First] INFO - leave synchronized monitor
2016-03-14 23:17:54,787 [Second] INFO - enter synchronized monitor
2016-03-14 23:18:04,787 [Second] INFO - leave synchronized monitor

如果两个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();

执行最新的代码,看看打印的执行结果。
Output:
2016-03-14 23:24:34,626 [First] INFO - enter synchronized monitor
2016-03-14 23:24:44,628 [First] INFO - leave synchronized monitor
2016-03-14 23:24:44,628 [Second] INFO - enter synchronized monitor
2016-03-14 23:24:54,630 [Second] INFO - leave synchronized monitor

两个Business实例的场景就不测了。
因为是静态方法嘛。

其它IntelliJ IDEA就已经提示出来了:
这种使用静态方法是需要重构的

- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
