1. 要求
- 线程Count负责报数字
- 线程Master负责监听键盘输入,一旦输入的是大写字母S,线程Count就退出报数字,线程Master也退出
2. 代码
- 以下代码都没有包含包信息,复制代码请注意随机应变
- MyPanel : 绘画板,是监听按键的载体
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class MyPanel extends JPanel implements KeyListener{
private int keyCode;
public int getKeyCode(){
return keyCode;
}
@Override
public void paint(Graphics g){
super.paint(g);
g.setColor(Color.green);
g.setFont(new Font("宋体", Font.BOLD, 20));
g.drawString("我是监控器,点击S结束count线程",20,110);
}
@Override
public void keyTyped(KeyEvent e){
}
@Override
public void keyPressed(KeyEvent e){
keyCode = e.getKeyCode();
}
@Override
public void keyReleased(KeyEvent e){
}
}
public class Count extends Thread{
private int count;
private boolean loop = true;
@Override
public void run(){
while(loop){
System.out.println("Count = " + (++count));
try{
Thread.sleep(5000);
}catch(InterruptedException e){
System.out.println("被终止了呢!那就不要数数了!");
}
}
}
public void setLoop(boolean loop){
this.loop = loop;
}
}
public class Master extends Thread{
private final JFrame frame = new JFrame();
private final MyPanel panel = new MyPanel();
private final Count thread;
{
frame.add(panel);
frame.addKeyListener(panel);
frame.setSize(400,400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public Master(Count thread){
this.thread = thread;
}
@Override
public void run(){
while(true){
int key = panel.getKeyCode();
try{
Thread.sleep(1);
}catch(InterruptedException e){
e.printStackTrace();
}
if(key == KeyEvent.VK_S){
thread.setLoop(false);
if(thread.getState() == State.TIMED_WAITING){
thread.interrupt();
}
break;
}
}
}
}
public class Test{
public static void main(String[] args) throws InterruptedException{
Count count = new Count();
Master master = new Master(count);
count.start();
master.start();
}
}
3. 疑问
- 在Master线程的run方法中,不知道为什么一定要有一个缓冲的代码才能实现功能,如果直接判断
if(key == KeyEvent.VK_S){}
,根本进不去,也不不知道为什么,百思不得其解,希望有大佬指点一下!