62,614
社区成员
发帖
与我相关
我的任务
分享
public class LazyInitialization {
private static Resourse resourse;
public static Resourse getInstance() {
if (resourse == null) {
resourse = new Resourse(1, "skywalker");
}
return resourse;
}
public class LazyInitialization {
private static Resourse resourse;
public static Resourse getInstance() {
if (resourse == null) {
resourse = new Resourse(1, "skywalker");
}
return resourse;
}
private static class Worker implements Runnable {
private final CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
try {
latch.await();
System.out.println(getInstance());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(1);
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
new Thread(new Worker(latch)).start();
latch.countDown();
}
}
public class Resourse {
private int id;
private String name;
public Resourse(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Resourse [id=" + id + ", name=" + name + "]";
}