- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建一个简单的java程序,其GUI是在Eclipse中的窗口生成器的帮助下构建的。GUI 仅包含一个按钮。
我的目标:- 单击按钮时,启动一个线程,该线程将无限地打印到控制台数字,直到再次单击同一按钮将其停止。
这是我的实现:-
Runner.java(线程类)
public class Runner extends Thread{
private volatile boolean running = true;
private int i = 1;
@Override
public void run() {
while(running)
{
System.out.println(i++ +"\n");
try {
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void shutdown()
{
running = false;
}
}
MainGUI.java(ui 类)
Runner runIT = new Runner();
final JButton btnNewButton = new JButton("Start Thread");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String buttonText = btnNewButton.getText();
if(buttonText.equals("Start Thread"))
{
btnNewButton.setText("Stop Thread");
runIT.start();
}
else if(buttonText.equals("Stop Thread"))
{
btnNewButton.setText("Start Thread");
runIT.shutdown();
}
}
});
我的问题:- 线程完美地启动和停止,但只有一次。也就是说,我只能启动和停止线程一次。当我尝试重新启动已停止的线程时,它失败了。我希望线程从停止时的相同值继续打印数字。
Error :- Exception in thread "AWT-EventQueue-0" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:705)
at com.zakoi.java.thread.GUI.MainGUI$2.actionPerformed(MainGUI.java:62)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6516)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3311)
at java.awt.Component.processEvent(Component.java:6281)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4872)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4698)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
请帮忙。
最佳答案
您应该让线程运行,但充当服务。然后应该通过某种形式的通信来控制它。
创建线程的成本相当高 - 不必要时不应创建/销毁它们。
这段代码使用锁来实现一个可以暂停和恢复的Thread
。这里的内容比您想要的要多一些,但它演示了理论。
/**
* PauseableThread is a Thread with pause/resume and cancel methods.
*
* The meat of the process must implement `step`.
*
* You can either extend this and implement `step` or use the factory.
*
* I cannot extend Thread because my resume will clash.
*
*/
public abstract class PauseableThread implements Runnable {
// The lock.
private final ReadWriteLock pause = new ReentrantReadWriteLock();
private final Lock readLock = pause.readLock();
private final Lock writeLock = pause.writeLock();
// Flag to cancel the wholeprocess.
private volatile boolean cancelled = false;
// The exception that cause it to finish.
private Exception thrown = null;
// The thread that is me.
private Thread me = null;
@Override
// The core run mechanism.
public void run() {
// Track my current thread.
me = Thread.currentThread();
try {
while (!finished()) {
// Block here if we're paused.
blockIfPaused();
// Don't do any more work if we've been asked to stop.
if (!finished()) {
// Do my work.
step();
}
}
} catch (Exception ex) {
// Just fall out when exception is thrown.
thrown = ex;
}
}
// Have we finished yet?
private boolean finished() {
return cancelled || !me.isInterrupted();
}
// Block if pause has been called without a matching resume.
private void blockIfPaused() throws InterruptedException {
try {
// Grab a write lock. Will block if a read lock has been taken.
writeLock.lockInterruptibly();
} finally {
// Release the lock immediately to avoid blocking when pause is called.
writeLock.unlock();
}
}
// Pause the work. NB: MUST be balanced by a resume.
public void pause() {
// We can wait for a lock here.
readLock.lock();
}
// Resume the work. NB: MUST be balanced by a pause.
public void resume() {
// Release the lock.
readLock.unlock();
}
// Stop.
public void cancel() {
// Stop everything.
cancelled = true;
}
// Stop immediately (if param is true).
public void cancel(boolean interrupt) {
if (interrupt) {
// Interrupt me.
me.interrupt();
} else {
// Or cancel me.
cancel();
}
}
// Wait for completion.
public void await() throws InterruptedException {
// Wait 'till we've finished. NB: Will wait forever if you haven't instigated a cancel of some kind.
while (me.isAlive()) {
Thread.sleep(0);
}
}
// Start - like a thread.
public void start() {
// Wrap me in a thread and fire the sucker up!
new Thread(this).start();
}
// Get the exception that was thrown to stop the thread or null if the thread was cancelled.
public Exception getThrown() {
return thrown;
}
// Expose my Thread.
public Thread getThread() {
return me;
}
// Create this method to do stuff.
// Calls to this method will stop when pause is called.
// Any thrown exception stops the whole process.
public abstract void step() throws Exception;
// Factory to wrap a Stepper in a PauseableThread
public static PauseableThread make(Stepper stepper) {
StepperThread pauseableStepper = new StepperThread(stepper);
// That's the thread they can pause/resume.
return pauseableStepper;
}
// One of these must be used.
public interface Stepper {
// A Stepper has a step method.
// Any exception thrown causes the enclosing thread to stop.
public void step() throws Exception;
}
// Holder for a Stepper.
private static class StepperThread extends PauseableThread {
// The actual stepper I am proxying.
private final Stepper stepper;
StepperThread(Stepper stepper) {
this.stepper = stepper;
}
@Override
public void step() throws Exception {
stepper.step();
}
}
// !!!! Testing only below !!!!
// My test counter.
static int n = 0;
// Test/demo.
public static void main(String[] args) throws InterruptedException {
try {
// Simple stepper that just increments n.
Stepper s = () -> {
n += 1;
Thread.sleep(1);
};
PauseableThread pt = PauseableThread.make(s);
// Start it up.
pt.start();
Thread.sleep(1000);
pt.pause();
System.out.println("Paused: " + n);
Thread.sleep(1000);
System.out.println("Resuminng: " + n);
pt.resume();
Thread.sleep(1000);
pt.cancel();
System.out.println("Finished: " + n);
// Start again to test agressive cancelling.
pt.await();
n = 0;
pt = PauseableThread.make(s);
// Start it up.
pt.start();
Thread.sleep(1000);
pt.pause();
System.out.println("Paused: " + n);
Thread.sleep(1000);
System.out.println("Resuminng: " + n);
pt.resume();
Thread.sleep(1000);
// Cancel aggressively.
pt.cancel(true);
System.out.println("Finished: " + n);
System.out.println("thrown: " + pt.getThrown());
} catch (InterruptedException e) {
}
}
}
关于在 Eclipse 中单击同一按钮上的 Java 线程启动-停止-启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26011376/
我在选项卡中有我的网络应用程序的选项。 aaa bbb ccc ddd eee 当用户单击任何选项卡(在同一窗口中)时,我会使用此代码获得淡出效果,然后自动
如何获得一个简单的调用单击来实现如下功能:http://jsfiddle.net/ftwPS/6/我显然错过了一些基本的东西,因为当您单击“CLICK”时这不起作用。 $('tr').click(fu
我有一个列表,在左侧显示一个插入符号图标,单击它时应该更改图标。每当我单击一个图标时,所有图标都会更改。 detailedInfo = []; subordinateInfo; openSu
我有一个 div,我想对其进行设置,以便当我单击其他内容时,它会隐藏该 div。 我也是这样 $('body').click(function(){ if(loginOpened) {
我有很多装有不同内容的盒子。 如果单击第一个框,您可以看到一个包含更多详细信息的弹出框。如果单击第二个、第三个等框,您必须查看这些框的详细信息。 我的问题:如果我点击框号。 2 我看到了盒子号的详细信
当我点击 .add-btn 时,我将 .add-btn 的样式更改为 background:#cccccc 并将 val() 更改为“-”。 现在当我用 tr td .list 删除添加的文本时,它是
感谢 SO 的出色贡献者!当您开始了解 jQuery 时,它会变得更酷。 :) 所以我有一个 LI,单击时会显示/隐藏子 UL。我想做的是能够单击 LI 内的链接,打开一个空白窗口,但也不会关闭子 U
我有这份文档,它使我能够获得一份带有点击进度的多项选择选择调查问卷。 如何用图像代替此处的文字? (并且仍然有这样的机制,一旦单击[图像],就会提出下一个问题) 我已经尝试使用 UL/H1 设置背景图
我想在 JQGrid 的刷新按钮单击上编写代码。有什么事件吗? 最佳答案 如果您需要在开始刷新之前执行一些操作,您应该使用 beforeRefresh打回来: $("#grid_id").jqGrid
问题是将对象或多个参数从模板传递到组件,并使用它们将数据添加到 API。 任务.service.ts addTasks(task: Task): Observable{ let headers =
我有一个像这样的primefaces选项卡 View : This tab has static content. this t
我在 jquery 中有一个有效的 a.click() 函数...但是如果我单击一个 anchor ,我会打开一个新窗口...但是我怎样才能阻止浏览器本身打开一个新窗口? 示例: $('a')
有没有简单的方法来创建代码:如果 URL 更改或单击链接显示 div(例如加载 gif 3 秒),则显示页面?有点像空白的白色页面,加载 gif 旋转 3 秒然后显示页面? 谢谢! 最佳答案 给定 G
我需要知道此时按钮的状态是否被点击? 谢谢 最佳答案 if (myButton.state & UIControlStateHighlighted) { // Do your stuff the
我正在 NSImageView 上绘制一条 NSBezierPath 线。我正在创建 NSBezierPath 对象,设置 moveToPoint,设置 lineToPoint,设置 setLineW
我的 Selenium 代码存在问题,无法正确执行按键 + 单击操作。 测试应打开 jqueryui.com 链接并选择页面上的前 2 个 li 元素。 我正在使用 Selenium 2.23 和 F
单击时我将更改字符串一部分的样式。例如“TEXT”,然后单击“T”,之后它会将样式从黑色更改为红色,仅 T在我的代码中,当我单击文本时,我拆分文本并保留在“split”数组中,它将调用handleCl
我在网站上有一个 anchor 。当有人点击它时,我在 jquery 中执行一些操作并更改名称,但是当再次单击它时,事件被触发,尽管我已经更改了它的名称。代码在这里: $(".like_cont a[
我有一个下载链接Download我希望每次当有人点击“下载”时,我都可以将其插入数据库total_downloads+1。为了插入数据库,我通常使用 然后 if (isset($_POST['d
我是一名优秀的程序员,十分优秀!