代码,BankAccount类部分:
package dodo;
public class BankAccount implements Runnable
{
private int balance=2000; // 账户余额
public BankAccount()
{
this.balance = balance;
}
// 存款方法,对方法进行同步
public synchronized void deposit(int amount)
{
balance += amount;
System.out.println(Thread.currentThread().getName() + " 存入 " + amount + " 元,余额为:" + balance);
}
// 取款方法,对方法进行同步
public synchronized void withdraw(int amount)
{
if (balance >= amount)
{
balance -= amount;
System.out.println(Thread.currentThread().getName() + " 取出 " + amount + " 元,余额为:" + balance);
}
else
{
System.out.println(Thread.currentThread().getName() + " 余额不足,无法取款,余额为:" + balance);
}
}
// 存款客户线程的运行体
public void depositTask()
{
for (int i = 0; i < 3; i++)
{
deposit(100);
try
{
Thread.sleep(1000); // 暂停1秒钟
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
// 取款客户线程的运行体
public void withdrawTask()
{
for (int i = 0; i < 4; i++)
{
withdraw(100);
try
{
Thread.sleep(1000); // 暂停1秒钟
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public void run()
{
// 获取当前线程对象
//Thread.currentThread()是Thread类中的一个静态方法,它返回当前正在执行的线程对象
Thread currentThread = Thread.currentThread();
// 获取当前线程的名称
String threadName = currentThread.getName();
// 判断当前线程是存款客户1还是存款客户2
if (threadName.equals("存款客户1") || threadName.equals("存款客户2"))
{
// 如果是存款客户1或存款客户2,执行存款操作
depositTask();
}
else if (threadName.equals("取款客户1") || threadName.equals("取款客户2"))
{
// 如果是取款客户1或取款客户2,执行取款操作
withdrawTask();
}
}
}
代码,main函数部分:
package dodo;
public class Dodo
{
public static void main(String[] args)
{
// 创建银行账户
BankAccount account = new BankAccount();
// 创建存款客户线程和取款客户线程,并启动线程
Thread th1 = new Thread(account, "存款客户1");
Thread th2 = new Thread(account, "取款客户1");
Thread th3 = new Thread(account, "存款客户2");
Thread th4 = new Thread(account, "取款客户2");
th1.start();
th2.start();
th3.start();
th4.start();
}
}