📄 example0902_synchronized1.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example0902_Synchronized extends JFrame implements ActionListener
{
JTextField inputMoney;
JButton setMoney;
JButton getMoney;
JTextArea list;
Account account;
public Example0902_Synchronized()
{
super("Synchronized");
setDefaultCloseOperation(EXIT_ON_CLOSE);
inputMoney = new JTextField(8);
setMoney = new JButton("购货商存款");
setMoney.addActionListener(this);
getMoney = new JButton("供货商取款");
getMoney.addActionListener(this);
list = new JTextArea(20, 30);
list.setEditable(false);
JPanel p = new JPanel();
p.add(new JLabel("请输入应付款"));
p.add(inputMoney);
p.add(setMoney);
p.add(getMoney);
Container con = getContentPane();
con.add(p, "North");
con.add(new JScrollPane(list), "Center");
setVisible(true);
pack();
account = new Account(list);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == setMoney)
{
String mstr = JOptionPane.showInputDialog(this, "请输入存款金额");
int m = Integer.parseInt(mstr);
account.setMoney(m);
}
if (evt.getSource() == getMoney)
{
int m = Integer.parseInt(inputMoney.getText());
account.getMoney(m);
}
}
public static void main(String[] args)
{
new Example0902_Synchronized();
}
}
class Account
{
int money = 0;
JTextArea list;
public Account(JTextArea list)
{
this.list = list;
this.list.append("当前帐户余额为:" + money + "(元)\n");
}
public void setMoney(int m)
{
synchronized(this)
{
money += m;
list.append("购货商存入:" + m + "(元),当前余额为:" + money + "(元)\n");
}
}
public boolean getMoney(int m)
{
synchronized(this)
{
while (m > money)
{
list.append("余额不足,交易不能完成,等待中...!\n");
return false;
}
money -= m;
list.append("交易完成,当前余额为:" + money + "(元)\n");
return true;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -