4

用两个锁解决单例模式的同步

 8 months ago
source link: https://www.jdon.com/18694.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

用两个锁解决单例模式的同步

public class Singleton {

private static Singleton instance = null;

static int i = 0;
//建实例锁 锁命令: i++ ,所有线程都可以开锁就是: i-- 命令,
//开锁的可能需要重新锁上。只有有资格建立实例的不用重新锁,有资格建立实例的条件时第一个开锁

static int j = 0;
//监视器 当多个实例开锁时监视是否有最先开锁的

public static Singleton getInstance() {

if (instance == null && i == 0) {
//如果没有实例,并且线程被锁(就是没线程可以最先开锁)

i++;
//进门就关门
j++;
//开始监视

//“开锁-重锁” 循环过程。 最先开锁的线程可以不重锁以建实例
while (i == j) {
//循环 如果没有一个线程能最先开锁
//则此次过程失败,循环下去.

i--; //开锁

if (j == i + 1) {
//本线程最先开锁,可以不重锁
instance = new Singleton();
//建实例,不重锁
}
else {
//不是第一个开锁的,可能和其线程一起开锁,也可能落后其他线程

i++;
//重锁

while (instance == null) {
//已经有线程最先开锁 只是没建完实例。等待
try {
Thread.sleep(1);
}
catch (InterruptedException ex) {

return instance;

关于JSP 实例方法的线程安全

我测试了下面的代码段,可还是得不出个结论来,还请各位大虾指点迷津。 代码如下: -------- .

一般的bean这种对象是不是存在线程步安全问题

比如 public class MyBean { private Stri.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK