[Java]_ch14.3_執行緒的同步問題
package YPU;
class Bank{
static int sum=0;
public synchronized static void add(int n){
int tmp=sum;
tmp=tmp+n;
try {
Thread.sleep((int)(Math.random()*100));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sum=tmp;
System.out.println("sum="+sum+"..."+Thread.currentThread().getName());
}
}
class Customer implements Runnable{
@Override
public void run() {
for(int i=0;i<3;i++)
Bank.add(100);
}
}
public class A14_1 {
public static void main(String[] args) {
Customer c1=new Customer();
Customer c2=new Customer();
Thread t1=new Thread(c1,"客戶1:");
Thread t2=new Thread(c2,"客戶2:");
t1.start();
t2.start();
}
}
沒有留言:
張貼留言