📄 startorstop.java
字号:
import java.awt.*;
import java.awt.event.*;
class Win extends Frame implements Runnable,ActionListener
{
Thread moveOrStop;
Button start,hang,resume,die;
Label moveLabel;
boolean move=false,dead=false;
Win()
{
moveOrStop=new Thread(this); //创建线程moveOrStop,当前窗口为moveOrStop的目标对象。
start=new Button("线程开始");
hang=new Button("线程挂起");
resume=new Button("线程恢复");
die=new Button("线程终止");
start.addActionListener(this);
hang.addActionListener(this);
resume.addActionListener(this);
die.addActionListener(this);
moveLabel=new Label("线程负责运动我");
moveLabel.setBackground(Color.red);
setLayout(new FlowLayout());
add(start);
add(hang);
add(resume);
add(die);
add(moveLabel);
setSize(500,500);
validate();
setVisible(true);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==start)
{
try {
move=true;
moveOrStop.start(); //启动线程moveOrStop。
}
catch(Exception event)
{
}
}
else if(e.getSource()==hang)
{
move=false;
}
else if(e.getSource()==resume)
{
move=true;
resumeThread(); //调用resumeThread()方法恢复线程。
}
else if(e.getSource()==die)
{
dead=true;
}
}
public void run()
{
while(true)
{
while(!move)
{
try{
hangThread(); //调用hangThread()方法挂起线程。
}
catch(InterruptedException e1)
{
}
}
int x=moveLabel.getBounds().x;
int y=moveLabel.getBounds().y;
y=y+2;
if(y>=200) y=10;
moveLabel.setLocation(x,y);
try{
moveOrStop.sleep(200);
}
catch(InterruptedException e2)
{
}
if(dead==true)
{
return; //结束run()方法终止线程。
}
}
}
public synchronized void hangThread() throws InterruptedException
{
wait(); //调用wait()方法。
}
public void resumeThread()
{
notifyAll() ; //调用notifyAll()方法。
}
}
public class StartOrStop
{
public static void main(String args[])
{
Win win=new Win();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -