package packMutil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Muti1 extends WindowAdapter implements ActionListener
{
public static JFrame f = new JFrame("Welcome");
public static MyThread mt1 = new MyThread("Welcome!");
public static MyThread mt2 = new MyThread("How are you?");
public static void main(String args[])
{
Muti1 ltr = new Muti1();
ltr.dispaly();
mt1.start();
mt1.setButton();
mt2.start();
mt2.setButton();
}
public void dispaly()
{
f.setSize(400,240);
f.setLocation(200,140);
f.setBackground(Color.LIGHT_GRAY);
f.setLayout(new GridLayout(4,1));
f.addWindowListener(this);
f.setVisible(true);
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void actionPerformed(ActionEvent e)
{
if((e.getSource()==mt1.aButton)||(e.getSource()==mt1.bButton))
{
actionPerformed(e,mt1);
}
if((e.getSource()==mt2.aButton)||(e.getSource()==mt2.bButton))
{
actionPerformed(e,mt2);
}
}
public void actionPerformed(ActionEvent e,MyThread mt)
{
if(e.getSource() == mt.aButton)
{
mt.SleepTime = Integer.parseInt(mt.bField.getText());
mt.setButton();
}
if(e.getSource() == mt.bButton)
{
mt.interrupt();
mt.setButton();
}
}
}
package packMutil;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.String;
public class MyThread extends Thread {
JPanel p;
JLabel alabel;
JTextField aField;
JTextField bField;
JButton aButton;
JButton bButton;
//随机睡眠时间
int SleepTime = (int)(Math.random()*100);
//构造函数
public MyThread(String str)
{
super(str); //调用父类的含参构造函数
for(int i=0;i<100;i++)
{
str = str +" ";
}
aField = new JTextField(str);
Muti1.f.add(aField);
p = new JPanel();
p.setLayout(new FlowLayout(FlowLayout.LEFT));
alabel = new JLabel("Sleep");
bField = new JTextField(""+SleepTime);
p.add(alabel);
p.add(bField);
aButton = new JButton("启动");
bButton = new JButton("中断");
p.add(aButton);
p.add(bButton);
aButton.addActionListener(new Muti1());
bButton.addActionListener(new Muti1());
Muti1.f.add(p);
Muti1.f.setVisible(true);
}
public void run()
{
String str;
while(true)
{
try
{
str = aField.getText();
str = str.substring(1)+str.substring(0,1);
aField.setText(str);
this.sleep(SleepTime);
}catch(InterruptedException e){
break;
}
}
}
public void setButton()
{
if(this.isAlive())
{
bButton.setEnabled(true);
aButton.setEnabled(false);
}
if(this.interrupted())
{
aButton.setEnabled(true);
bButton.setEnabled(false);
}
}
}