【发布时间】:2015-06-22 21:53:05
【问题描述】:
我正在使用鼠标监听器来监听鼠标的按下和释放。当鼠标被按下时,我想让一个计数器增加一个变量,当鼠标被释放时,我想减少那个变量。现在,我的代码正在工作,但增量太快了,我想放慢它,因为我在游戏中使用这些数字作为坐标。我尝试添加一个 Thread.sleep(100) 但我得到了倾斜的输出。看起来多个线程同时进行,我到处都是数字。下面是示例代码。
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.lang.*;
public class Sample extends JFrame {
private JPanel jp = new JPanel();
int i = 0;
boolean once = true;
boolean on = true;
Thread t1 = new Thread(new Increase());
Thread t2 = new Thread(new Decrease());
public sample() {
setVisible(true);
setSize(300, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(jp);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent event) {
if (!once) //false
{
t2.interrupt();
}
if (once) //true
{
once = false;
t1.start();
}
else {
t1 = new Thread(new Increase());
t1.start();
}
}
public void mouseReleased(MouseEvent event) {
t1.interrupt();
if (on) //true
{
on = false;
t2.start();
}
else {
t2 = new Thread(new Decrease());
t2.start();
}
}
});
}
public static void main(String[] args) {
new Sample();
}
public int getI() {
return i;
}
public void setI(int num) {
i = num;
}
class Increase implements Runnable {
public void run() {
int num = getI();
while (!Thread.currentThread().isInterrupted()) {
try {
setI(++num);
Thread.sleep(100);
System.out.println(num);
}
catch (InterruptedException e) {
}
}
}
}
//Thread.currentThread().isInterrupted()
class Decrease implements Runnable {
public void run() {
int num = getI();
while (!Thread.currentThread().isInterrupted()) {
try {
setI(--num);
Thread.sleep(100);
System.out.println(num);
}
catch (InterruptedException e) {
}
}
}
}
}
【问题讨论】:
-
为什么需要
Thread?另外,线程是不可重入的,即一旦退出就无法重启 -
您可以使用单个 Swing
Timer和一个增量值来安全地实现相同的目标 -
代码按照您编写的方式运行。
-
@MadProgrammer 如果不使用单独的线程,我会在执行 while(pressed) i++ 时陷入无限循环,并且在释放鼠标时无法退出。如果您对如何做到这一点有其他建议,我愿意改变我目前的策略
-
@SpencerSprowls 您错过了重点,您想要增加或减少值。
Timer会定期给您回电。使用增量(变化值),您可以影响i的方向
标签: java multithreading