大家帮我看看这个多线程计时器哪里出错了?

halw002 2017-06-08 10:48:15
要求是:要用多线程做一个计时器,有开始和停止(清空)功能。。完全没有头绪

package csteaching;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public class C2 extends JFrame implements ActionListener,Runnable{
Thread t;
String threadName;
JTextField t1;
JButton b1;
JButton b2;
boolean flag = false;
int h=0,m=0,s=0;

public C2(){
super("TIME");
setSize(600,400);
setLayout(new GridLayout(3,1));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t1=new JTextField();
b1=new JButton("Start");
b2=new JButton("Stop");
add(t1);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}

public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("Start")){
flag=true;
}
else{
flag=false;
h=0;
m=0;
s=0;
}
}

public void run(){
if(Thread.currentThread().getName().equals("timer")){
while(flag){
Timer();
}
}
if(Thread.currentThread().getName().equals("show_time")){
show_time();
}
}

public void Timer(){
try{
Thread.currentThread().sleep(1000);
}catch (InterruptedException e) {}
s++;
if(s==61){m++;s=0;}
if(m==61){h++;m=0;}
}

public void show_time(){
t1.setText(h+":"+m+":"+s);
}

public static void main(String[] args) throws InterruptedException {
C2 tt = new C2();
tt.setVisible(true);
Thread t1=new Thread(tt);
Thread t2=new Thread(tt);
t1.setName("timer");
t2.setName("show_time");
t1.start();
t2.start();
}
}
...全文
106 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

51,411

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧