[size=x-large]
public class Bank implements Runnable {
private int money;
Thread th=new Thread();
public void run() {
for(int i = 0 ;i<12;i++){
int temp ;
temp=money;
money+=1000;
System.out.println( th.currentThread().getName()+"余的钱"+money );
}
try {
th.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String []args){
Bank b=new Bank();
Thread th1=new Thread (b,"爸爸存入了1000");
Thread th2= new Thread(b,"妈妈存入了1000");
th1.start();
th2.start();
}
}
public class Test2 extends Thread {
private static int money;
public synchronized void run() {
for (int i = 0; i < 12; i++) {
int temp;
money += 1000;
temp = money;
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("存款" + money + "余的钱" + temp);
}
}
public static void main(String[] args) {
Test2 t = new Test2();
t.start();
Test2 t2 = new Test2();
t2.start();
}
}
用synchronized可能会产生死锁。
[/size]
public class Bank implements Runnable {
private int money;
Thread th=new Thread();
public void run() {
for(int i = 0 ;i<12;i++){
int temp ;
temp=money;
money+=1000;
System.out.println( th.currentThread().getName()+"余的钱"+money );
}
try {
th.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String []args){
Bank b=new Bank();
Thread th1=new Thread (b,"爸爸存入了1000");
Thread th2= new Thread(b,"妈妈存入了1000");
th1.start();
th2.start();
}
}
public class Test2 extends Thread {
private static int money;
public synchronized void run() {
for (int i = 0; i < 12; i++) {
int temp;
money += 1000;
temp = money;
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("存款" + money + "余的钱" + temp);
}
}
public static void main(String[] args) {
Test2 t = new Test2();
t.start();
Test2 t2 = new Test2();
t2.start();
}
}
用synchronized可能会产生死锁。
[/size]