如果我想用两个不同的线程更新单个对象,我该怎么办?
我试过了:
public class BankAccount{
private static int balance;
private static void balance(int amt)throws InterruptedException{
balance = amt;
Thread thread = new Thread(new Runnable(){
@Override
public void run(){
try {
balance(10);
System.out.println("Initial Balance:\t"+balance);
} catch (InterruptedException ex) {
System.out.println("Exception"+ex.getMessage());
}
}
});
thread.start();
TimeUnit.SECONDS.sleep(5);
}
private static void deposit(int deposit){
balance+=deposit;
}
public static void main(String[] args)throws InterruptedException {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
deposit(10);
System.out.println("Balance after deposit\t"+balance);
}
});
thread.start();
TimeUnit.SECONDS.sleep(5);
}
}
我知道使用单线程可以获得所需的输出:
初始余额:10
存款后的余额:20
但是如果有办法处理两个不同的线程。
答案 0 :(得分:-1)
您需要按照以下步骤操作:
(1)使用balance
作为AtomicInteger
使其线程安全。
(2)首先定义showBalance()
,setBalance(int amt)
和deposit(int deposit)
方法(在您的代码中balance(int)
未正确命名,将其称为setBalance(int amt)
它更有意义)
(3)创建thread1并调用setBalance(int amt)
(4)创建thread2并调用showBalance()
(5)创建thread3并调用deposit(int amt)
(5)启动线程
您可以参考以下代码:
private static AtomicInteger balance = new AtomicInteger();
private static void showBalance() {
return balance.get();
}
private static void setBalance(int amt) {
balance.set(amt);
}
private static void deposit(int deposit){
balance.getAndAdd(deposit);
}
public static void main(String[] args)throws InterruptedException {
Thread thread1 = new Thread(new Runnable(){
@Override
public void run() {
setBalance(10);
System.out.println("Initial Balance\t"+balance);
}
});
thread1.start();
thread1.join();//join after completion of thread1
//(i.e., displays Initial Balance)
Thread thread2 = new Thread(new Runnable(){
@Override
public void run() {
showBalance();
System.out.println(" Balance\t"+balance);
}
});
thread2.start();
thread2.join();
Thread thread3 = new Thread(new Runnable(){
@Override
public void run() {
deposit(10);
System.out.println("Balance after deposit\t"+balance);
}
});
thread3.start();
}