我有一个使用单例模式的程序。我需要使用线程,记住使用线程机械化之前和之后的输出应该是相同的。我的意思是避免线程忽略单例并创建更多一个对象的“断线模式”。但是,我失败了。我试图使用“同步”,但没有改变。同样的错误结果。
我的主要与Runnable
public class Main implements Runnable {
Main(){}
public void run ()
{
Counter[] counters = new Counter[5];
for(int i = 0; i < counters.length; i++)
{
counters[i] = Counter.getCounter();
}
for(int i = 0; i < counters.length; i++)
{
counters[i].increment();
System.out.println("counter[" + i + "] = " + counters[i]);
}
for(int i = 0; i < 5; i++) {
counters[i].decrement();
System.out.println("counter[" + i + "] = " + counters[i]);
}}
public static void main(String[] args)
{
Main m1=new Main();
Main m2=new Main();
Main m3=new Main();
new Thread(m1).start();
new Thread(m2).start();
new Thread(m3).start();
}
}另一个应用单例模式的类
public class Counter {
private static Counter myInstance = null;
public static Counter getCounter()
{
if(myInstance == null)
{
synchronized (Counter.class) {
if(myInstance == null)
{
myInstance = new Counter();
}
}
}
return(myInstance);
}
private int myCounter;
private Counter() {
myCounter = 0;
}
public void increment() {
myCounter++;
}
public void decrement() {
myCounter--;
}
public String toString() {
return(Integer.toString(myCounter));
}
}