📄 runnabledemo.java
字号:
//实现Runnable接口线程演示
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.*;
import java.util.*;
//通过实现Runnable接口创建线程
public class RunnableDemo extends JFrame implements Runnable,ActionListener
{
JPanel pnlMain;
JLabel lblTime;
JButton btnControl;
//声明一个用于显示时间的线程
Thread thdDisplayTime;
Date dateDisplay;
GregorianCalendar gcCalendar;
String strDate,strTime;
public RunnableDemo()
{
super("实现Runnable接口线程演示");
pnlMain=new JPanel(new GridLayout(2,1));
setContentPane(pnlMain);
lblTime=new JLabel("");
btnControl=new JButton("挂起");
btnControl.addActionListener(this);
pnlMain.add(lblTime);
pnlMain.add(btnControl);
//构造线程对象并让它处于运行状态
thdDisplayTime=new Thread(this);
thdDisplayTime.start();
setSize(250,150);
setVisible(true);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//实现Runnable接口必须实现的run方法
public void run()
{
while (thdDisplayTime!=null)
{
//调用显示时间函数显示当前时间
displayTime();
try
{
thdDisplayTime.sleep(1000);
}
catch(InterruptedException e)
{
JOptionPane.showMessageDialog(null,"线程中断!");
}
}
}
//实现ActionListener接口必须实现的方法
public void actionPerformed(ActionEvent ae)
{
//与前面不同的是,这里通过按钮上的文字进行相应处理
if (ae.getActionCommand()=="挂起")
{
btnControl.setText("重启");
thdDisplayTime.suspend();
}
if (ae.getActionCommand()=="重启")
{
btnControl.setText("挂起");
thdDisplayTime.resume();
}
}
//显示当前日期和时间的函数
public void displayTime()
{
dateDisplay=new Date();
gcCalendar=new GregorianCalendar();
//获得当前时间
gcCalendar.setTime(dateDisplay);
//从当前时间中提取日期段和时间段
strTime=" 当前时间:"+gcCalendar.get(Calendar.HOUR)+":"+gcCalendar.get(Calendar.MINUTE)+":"+gcCalendar.get(Calendar.SECOND);
strDate="今天日期:"+gcCalendar.get(Calendar.YEAR)+"-"+(gcCalendar.get(Calendar.MONTH)+1)+"-"+gcCalendar.get(Calendar.DATE);
//显示当前日期和时间
lblTime.setText(strDate+strTime);
}
public static void main(String args[])
{
RunnableDemo rd=new RunnableDemo();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -