class Account {
String name;
float amount;
// 这个是用于同步锁的静态对象
// private static byte[] arrB = new byte[0];
public Account(String name, float amount) {
this.name = name;
this.amount = amount;
}
public void deposit(float amt) {
float tmp = amount;
tmp += amt;
try {
// Thread.sleep((long)(Math.random()*10));//模拟其它处理所需要的时间,比如刷新数据库等
Thread.sleep(1000);//模拟其它处理所需要的时间,比如刷新数据库等
} catch (InterruptedException e) {
// ignore
System.out.println(e.getMessage());
}
amount = tmp;
}
public void withdraw(float amt) {
float tmp = amount;
tmp -= amt;
try {
// Thread.sleep((long)(Math.random()*10));//模拟其它处理所需要的时间,比如刷新数据库等
Thread.sleep(1000);//模拟其它处理所需要的时间,比如刷新数据库等
} catch (InterruptedException e) {
// ignore
System.out.println(e.getMessage());
}
amount = tmp;
}
public float getBalance() {
return amount;
}
}
public class AccountTest{
private static int NUM_OF_THREAD = 1000;
static Thread[] threads = new Thread[NUM_OF_THREAD];
// private static int nCount = 1000;
public static void main(String[] args){
byte[] arrB = new byte[0];
final Account acc = new Account("John", 1000.0f);
for (int i = 0; i< NUM_OF_THREAD; i++) {
threads[i] = new Thread(
new Runnable(){
public void run(){
acc.deposit(100.0f);
acc.withdraw(100.0f);
/*try{
acc.deposit(100.0f);
System.out.println(Thread.currentThread().getName()+"睡眠开始");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"睡眠结束");
acc.withdraw(100.0f);
// nCount--;
}
catch(InterruptedException ex){
System.out.println(ex.getMessage());
}
*/
}
}
);
threads[i].start();
}
for (int i=0; i<NUM_OF_THREAD; i++){
try {
threads[i].join(); //等待所有线程运行结束
} catch (InterruptedException e) {
// ignore
System.out.println(e.getMessage());
}
}
for(int i=0; i<NUM_OF_THREAD; i++){
if(threads[i].isAlive()){
System.out.println("线程"+(i+1)+"还活着");
}
}
// System.out.println("nCount:"+nCount);
//while(nCount>0);
System.out.println("Finally, John's balance is:" + acc.getBalance());
}
}
引用网址:http://www.cnblogs.com/devinzhang/archive/2011/12/14/2287675.html#commentform
这个程序的运行结果基本上是始终是1000.0,没有出现并发导致混乱的效果,同时还有就是整个程序的sleep时间很短,就相当于只睡眠2秒似的,尽管有1000个线程,为什么会出现这种情况呢?因为这里的sleep的作用相当于yield函数,具体解释:比如第1个线程sleep,然后cpu被第2个线程占用,然后第2个线程执行,也遇到sleep,第1,2两个线程的sleep间隔很短,基本上可以忽略,然后整1000个线程都类似这种情况,所以就相当于,1000个线程一起sleep似得。所以这是整个程序睡眠时间很短,还有就是结果总是会正确没有出现并发访问错误的原因。如果将sleep固定时间,改成随机时间,就会出现理想的效果,不过睡眠时间依然很短,比如改成“Thread.sleep((long)(Math.random()*10));”