tmp += amount; // 缓存累加之后的金额
try {
Thread.sleep(100); // 模拟处理需要的时间
} catch (Exception e) {
}
account.setAmount(tmp); // 写入操作
System.out.println(getBalance());
}
// 取钱
public synchronized void withdraw(double amount) {
double tmp = account.getAmount(); // 缓存现有金额
tmp -= amount;
try {
Thread.sleep(100); // 模拟处理需要的时间
} catch (Exception e) {
}
account.setAmount(tmp); // 写入操作
}
// 查询余额
public String getBalance() {
return account.getName() + "---" + account.getAmount();
}
}
public class ThreadDemo {
private static int NUM_OF_THREAD = 10;
static Thread[] threads = new Thread[NUM_OF_THREAD];
public static void main(String[] args) {
final Bank bank = new Bank(new Account("张三",3000.00d));
for (int i=0; i
@Override
public void run() {
bank.deposit(100.00d);
bank.withdraw(100.00d);
}
});
threads[i].start();
}
for (int i=0; i
threads[i].join();
} catch (Exception e) {}
}
System.out.println("余额:" + bank.getBalance());
}
}
class Account {
private String name;
private double amount;
public Account(String name, double amount) {
this.name = name;
this.amount = amount;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAmount(double amount) {
this.amount = amount;
}
public double getAmount() {
return this.amount;
}
}
class Bank {
private Account account;
public Bank(Account account) {
this.account = account;
}
// 存钱
public synchronized void deposit(double amount) {
double tmp = account.getAmount(); // 缓存现有金额
tmp += amount; // 缓存累加之后的金额
try {
Thread.sleep(100); // 模拟处理需要的时间
} catch (Exception e) {
}
account.setAmount(tmp); // 写入操作
System.out.println(getBalance());
}
// 取钱
public synchronized void withdraw(double amount) {
double tmp = account.getAmount(); // 缓存现有金额
tmp -= amount;
try {
Thread.sleep(100); // 模拟处理需要的时间
} catch (Exception e) {
}
account.setAmount(tmp); // 写入操作
}
// 查询余额
public String getBalance() {
return account.getName() + "---" + account.getAmount();
}
}
public class ThreadDemo {
private static int NUM_OF_THREAD = 10;
static Thread[] threads = new Thread[NUM_OF_THREAD];
public static void main(String[] args) {
final Bank bank = new Bank(new Account("张三",3000.00d));
for (int i=0; i
@Override
public void run() {
bank.deposit(100.00d);
bank.withdraw(100.00d);
}
});
threads[i].start();
}
for (int i=0; i
threads[i].join();
} catch (Exception e) {}
}
System.out.println("余额:" + bank.getBalance());
}
}其它常用方法:
object.wait()
wait()方法用在同步的代码块里,当wait()被执行时,锁会被释放,当前线程进入等待队列。
只有该对象的锁被释放,并不会释放当前线程持有的其他同步资源。
如果当前线程在等待之前或在等待时被任何线程中断,则会抛出InterruptedException。
object.notify()
方法notify()同样用在同步的代码块里。唤醒在此对象锁上等待的单个线程。此方法只能由拥有该对象锁的线程来调用。
notify()将通知等待相同锁的线程,如果有多个线程在等待这个锁,将从中随机选择一个进行通知。
从锁的等待队列里面随机唤醒某一个线程,唤醒之后的线程进入就绪队列,等待