我创建了一个线程组,包括100个线程,目的是让count中的balance这个int 类型数值从0++到99,但是当我在这个实现++的操作中加入了Thread.sleep(某个数字)的时候,发现不能实现,最后balance的值班很小加不到99,当我去掉以后就可以了,这是为什么呢??呵呵,请指教!!
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;public class smallSystem
{private count p=new count();
private Thread []thread=new Thread[100];
int i;
public smallSystem()
{ThreadGroup t=new ThreadGroup("group");
for( i=0;i<100;i++)
{thread[i]=new Thread(t,new accout(),"");
thread[i].start();
}
}
public static void main(String argv[])
{smallSystem q=new smallSystem();
q.p.out();
} //inner class
class accout extends Thread
{
public void run()
{p.add();
}
} //inner class
class count
{private int balance=0;
private String s=new String(); public synchronized void add()
{balance++;
s+=balance;
try{ //加了这段代码以后出现问题
Thread.sleep(5);
}
catch(Exception ex)
{
}
}
public void out()
{JOptionPane.showMessageDialog(null,s);
JOptionPane.showMessageDialog(null,"\n"+String.valueOf(i));
}
}
}
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;public class smallSystem
{private count p=new count();
private Thread []thread=new Thread[100];
int i;
public smallSystem()
{ThreadGroup t=new ThreadGroup("group");
for( i=0;i<100;i++)
{thread[i]=new Thread(t,new accout(),"");
thread[i].start();
}
}
public static void main(String argv[])
{smallSystem q=new smallSystem();
q.p.out();
} //inner class
class accout extends Thread
{
public void run()
{p.add();
}
} //inner class
class count
{private int balance=0;
private String s=new String(); public synchronized void add()
{balance++;
s+=balance;
try{ //加了这段代码以后出现问题
Thread.sleep(5);
}
catch(Exception ex)
{
}
}
public void out()
{JOptionPane.showMessageDialog(null,s);
JOptionPane.showMessageDialog(null,"\n"+String.valueOf(i));
}
}
}
smallSystem q = new smallSystem();
try {
Thread.sleep(2000);
} catch (Exception ex) { }
q.p.out();
}