这是我在这里的第一篇文章,所以希望它没有问题。尝试使用线程时程序锁定
我在netbeans。我用纽扣等做了一个窗口。
我有一个叫SimpleThread类,看起来像这样:
public class SimpleThread extends Thread {
public SimpleThread()
{
}
@Override
public void run()
{
}
而且我有各种不同的子类的线程扩展simplethread(TimerThread,MouseGrabThread)。
public class MouseGrabThread extends SimpleThread{
private Point pt;
private JTextField x, y;
public MouseGrabThread(JTextField x, JTextField y)
{
super();
this.x = x;
this.y = y;
}
@Override
public void run()
{
while(this.isAlive())
{
int[] xyVal = new int[2];
xyVal = getCoords();
x.setText("" + xyVal[0]);
y.setText("" + xyVal[1]);
}
}
public int[] getCoords()
{
Point pt = MouseInfo.getPointerInfo().getLocation();
int[] retArr = new int[2];
retArr[0] = (int)pt.getX();
retArr[1] = (int)pt.getY();
return retArr;
}
public class TimerThread extends SimpleThread {
private JTextArea label;
private int time;
public TimerThread(JTextArea label, int time)
{
super();
this.label = label;
this.time = time;
}
@Override
public void run()
{
int counter = time;
while(counter != -1)
{
label.setText("You have: " + counter + " seconds until the timer ends!\n");
counter--;
try {
this.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Thread Interrupted");
}
}
stop();
}
在我的UI窗口类,我有这样的:
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
SimpleThread timer = new TimerThread(jTextArea1, 10); //This counts down from 10 seconds and updates a status text box each second
SimpleThread mouseGrab = new MouseGrabThread(jTextField1, jTextField2); //This grabs mouse coords and updates two boxes in the UI.
timer.start();
if(timer.isAlive())
{
mouseGrab.start();
}
while(timer.isAlive())//######
{
if(!mouseGrab.isAlive())
{
mouseGrab.start();
}
}
}
程序冻结10秒钟时,我按下按钮。
我猜我已标记的行(// #####)是导致UI在定时器的持续时间内冻结的行,导致它在主线程中运行。我不知道如何解决这个问题。
请原谅我对编程知识的缺乏,现在我正在进入自己的线程,而我正在大学学习关于数据结构的非常简单的课程。如果可能的话,你能尽可能地“减弱”答案吗?另外,我知道我做这件事很糟糕,但我称之为stop()函数,即使它不好(不要为此拍摄我,我不知道该怎么办!)如果有人能够很好地回答这个问题,那太棒了!
如果我想继续GUI在倒计时时可用吗?现在,整个程序冻结,并且它不更新timerThread输出的文本框或鼠标坐标的X和Y textAreas。 – Pilapodapostache 2013-04-05 18:31:54
您的'TimerThread'可以引用'mouseGrab',因此'timer'本身可以决定何时打破它。请参阅我的(传入)** Edit2 **的插图。 – blint 2013-04-05 18:55:01
就是这样,谢谢! :) – Pilapodapostache 2013-04-06 19:31:26