📄 example09_synchronized_ticket.java
字号:
package example.ch09;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example09_Synchronized_Ticket extends JFrame implements ActionListener
{
JButton newBuyer;
JTextArea list;
Saler saler;
int no;
public Example09_Synchronized_Ticket()
{
super("Synchronized");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Font font = new Font("宋体", Font.BOLD, 20);
newBuyer = new JButton("创建一个买票者");
newBuyer.setFont(font);
newBuyer.addActionListener(this);
list = new JTextArea("waiting for buyer ...\n");
list.setFont(font);
list.setEditable(false);
Container con = getContentPane();
con.add(newBuyer, "North");
con.add(new JScrollPane(list), "Center");
setExtendedState(MAXIMIZED_BOTH);
setVisible(true);
saler = new Saler(list);
no = 1;
}
public void actionPerformed(ActionEvent evt)
{
Buyer buyer = new Buyer(saler, no ++);
buyer.start();
}
public static void main(String[] args)
{
new Example09_Synchronized_Ticket();
}
}
class Saler
{
JTextArea list;
int count, n5, n10;
public Saler(JTextArea list)
{
this.list = list;
count = n5 = n10 = 0;
}
public synchronized void saleTicket(int no, int giveMoney)
{
list.append("\nThe buyer No." + no + " holds " + giveMoney + " 元买票 ...\n");
if (giveMoney == 5)
{
n5 ++;
}
if (giveMoney == 10)
{
while (n5 < 1)
{
try
{
wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
n5 --;
n10 ++;
}
count ++;
list.append("\nThe buyer No." + no + " 买票成功!\n");
list.append(getResult() + "\n");
notifyAll();
}
public String getResult()
{
int money = n5 * 5 + n10 * 10;
String result = "Total = " + money + " ; " +
"Count = " + count + " ; " +
"n5 = " + n5 + " ; " +
"n10 = " + n10;
return result;
}
}
class Buyer extends Thread
{
Saler saler;
int no;
public Buyer(Saler saler, int no)
{
this.saler = saler;
this.no = no;
}
public void run()
{
int giveMoney = (int)(1 + Math.random() * 2) * 5;
saler.saleTicket(no, giveMoney);
}
}Money = (int)(1 + Math.random() * 2) * 5;
saler.saleTicket(no, giveMoney);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -