package Thread;
/**
* 线程之间的通信
* */
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TreadCommunicate extends JFrame{
public TreadCommunicate(){
panel.setLayout(new GridLayout(2, 2, 3, 3));
panel.add(label1);
panel.add(label2);
JScrollPane js1 = new JScrollPane(oneArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
panel.add(js1);
JScrollPane js2 = new JScrollPane(twoArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
panel.add(js2);
statrButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
Sender sender = new Sender();
Thread demo1 = new Thread(sender);
Thread demo2 = new Thread(new Receiver(sender));
demo1.start();
demo2.start();
}
});
panel2.add(panel);
panel2.add(statrButton);
setContentPane(panel2);
setSize(300, 400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args){
new TreadCommunicate();
}
/**
* 卖家
* */
class Sender implements Runnable{
@Override
public void run(){
for(int i = 0; i < 5; ++i){
// 如果已经发送,那么就等待
while(isValid){
Thread.yield();
}
product = products[i];
String text = oneArea.getText();
oneArea.setText(text + "发送" + product
+ "\n");
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
isValid = true;
}
}
public boolean isisValid(){
return this.isValid;
}
public void setValid(boolean flag){
this.isValid = flag;
}
public String getProduct(){
return product;
}
private volatile String[] products = { "《金
瓶梅》", "《红楼梦》", "《平凡的世界》",
"《流氓老师》", "《西游记》" };
private volatile boolean isValid = false;
private volatile String product;
}// end sender
/**
* 买家
* */
class Receiver implements Runnable{
public Receiver(){
}
public Receiver(Sender sender){
this.sender = sender;
}
@Override
public void run(){
for(int i = 0; i < 5; ++i){
// 如果没有发送,就等待
while(!sender.isisValid()){
Thread.yield();
}
String test = twoArea.getText();
twoArea.setText(test + "接受到" + sender.getProduct()
+ "\n");
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
sender.setValid(false);
}
}
private Sender sender;
}
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
private final JButton statrButton = new JButton("开始交易");
private final JLabel label1 = new JLabel("卖家");
private final JLabel label2 = new JLabel("买家");
private final JTextArea oneArea = new JTextArea(5,
10);
private final JTextArea twoArea = new JTextArea(5,
10);
} |