多线程

package TestCode;

import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class TestStatus extends WindowAdapter implements ActionListener {
 Frame f;
 static TestStatus.ThreadTest t1, t2;

 public static void main(String[] args) {

  TestStatus w = new TestStatus();
  w.display();
  t1 = w.new ThreadTest("Welcome to java world!");
  t2 = w.new ThreadTest("Welcome to study thread!");
  t2.start();
  t2.setButton();
 }

 public void display() {
  f = new Frame("Welcome");
  f.setSize(200, 200);
  f.setLocation(200, 140);
  f.setBackground(Color.lightGray);
  f.setLayout(new GridLayout(4, 1));
  f.addWindowListener(this);
  f.setVisible(true);
 }

 public class ThreadTest extends Thread {
  Panel p1;
  Label lb1;
  TextField tf1, tf2;
  Button b1, b2;
  int sleeptime = (int) (Math.random() * 100);

  public ThreadTest(String str) {
   super(str);
   for (int i = 0; i < 100; i++)
    str = str + "";
   tf1 = new TextField(str);
   f.add(tf1);
   p1 = new Panel();
   p1.setLayout(new FlowLayout(FlowLayout.LEFT));
   lb1 = new Label("sleep");
   tf2 = new TextField("" + sleeptime);
   p1.add(lb1);
   p1.add(tf2);
   b1 = new Button("启动");
   b2 = new Button("中断");
   p1.add(b1);
   p1.add(b2);
   b1.addActionListener(new TestStatus());
   b2.addActionListener(new TestStatus());
   f.add(p1);
   f.setVisible(true);
  }

  public void run() {
   String str;
   while (this.isAlive() && !this.isInterrupted()) {
    try {
     str = tf1.getText();
     str = str.substring(1) + str.substring(0, 1);
     tf1.setText(str);
     this.sleep(sleeptime);
    } catch (InterruptedException e) {
     System.out.println(e);
     break;
    }
   }
  }

  public void setButton() {
   if (this.isAlive())
    b1.setEnabled(false);
   if (this.isInterrupted())
    b2.setEnabled(false);
  }

 }

 public void windowClosing(WindowEvent e) {
  System.exit(0);
 }

 public void actionPerformed(ActionEvent e) {
  if ((e.getSource() == t1.b1) || (e.getSource() == t2.b2))
   actionPerformed(e, t1);
  if ((e.getSource() == t2.b1) || (e.getSource() == t2.b2))
   actionPerformed(e, t2);
 }

 public void actionPerformed(ActionEvent e, ThreadTest t1) {
  if (e.getSource() == t1.b1) {
   t1.sleeptime = Integer.parseInt(t1.tf2.getText());
   t1.start();
  }
  if (e.getSource() == t1.b2)
   t1.interrupt();
  t1.setButton();
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值