带暂停和恢复的Java线程化for循环
假设我有一个1000的for循环,它做了一些事情。我可以用“暂停”按钮进入暂停功能,用“恢复”按钮取消暂停 问题:对于这种情况,我需要实现一个线程吗带暂停和恢复的Java线程化for循环,java,loops,Java,Loops,假设我有一个1000的for循环,它做了一些事情。我可以用“暂停”按钮进入暂停功能,用“恢复”按钮取消暂停 问题:对于这种情况,我需要实现一个线程吗 for (int i = 0; i < 1000; i++) { // Do stuff pause(); } for(int i=0;i
for (int i = 0; i < 1000; i++) {
// Do stuff
pause();
}
for(int i=0;i<1000;i++){
//做事
暂停();
}
您可以使用布尔
标志:
public volatile boolean paused = false;
public final int littleTime = 100; //ms
for (int i = 0; i < 1000; ++i) {
// Do stuff
pause();
}
public void pause() {
paused = true;
while (paused)
try {
Thread.sleep(littleTime);
} catch (InterruptedException e) {}
}
public void resume() {
paused = false;
}
public=false;
公共期末智力测验时间=100//太太
对于(int i=0;i<1000;++i){
//做事
暂停();
}
公共空间暂停(){
暂停=真;
while(暂停)
试一试{
线程。睡眠(小时间);
}捕获(中断异常e){}
}
公众简历(){
暂停=错误;
}
如果我理解正确,答案是否定的,您不需要实现额外的线程。如果您遵循GUI程序的常规模式,那么该线程将在与主GUI线程不同的线程中运行,这就足够了
您需要在for循环的每次迭代中检查用户是否暂停了系统并等待恢复。这可以通过一个简单的通知信号模式来完成 如果暂停,则使用布尔值来声明
volatile boolean isPause=false;
对于(int i=0;i<1000;i++){
//如果没有通过,就做一些事情
如果(!i暂停)
doStuff();
}
注意:点击
Pause
按钮时,将isPause
标志设置为true
。点击Resume
按钮时,将isPause
标志重置为false。我还将boolean
标记为volatile
,以便始终从主内存(无缓存)读取变量,因为在这种情况下,读取和写入都是原子的我认为您需要一个线程,因为您显示的循环必须在工作线程中运行,而处理按钮按下事件的按钮和代码必须在GUI线程中运行。因此,您需要从GUI线程暂停工作线程 这实现了一个可暂停线程。请参阅顶部关于如何使用它的注释。参见main
方法中的用法示例
/**
* 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 = new Stepper() {
@Override
public void step() throws Exception {
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) {
}
}
}
暂停时,根据cpu的能力生成尽可能多的
noop
?您可以添加类似Thread.sleep(100)的内容
提高效率这是常见的反模式;)如果你在手机上尝试,用户会用石头砸你。泰迪尔提到了睡眠的任何原因。我认为邹必须在bool上使用volatile。而且,这会疯狂地破坏循环:)@mafu哈哈,KISS;)更正,谢谢!这么长的代码?你从哪里剪下来的?@newbieprogrammer-我自己的私人藏品。:)如果你打算经常做某事,你最好把它做好。这是我的正确方式。它将所有复杂的边缘情况移开,使暂停线程变得简单。没有旋转锁!不要等待/通知!无Thread.sleep()
(测试中以及绝对必要的情况除外)!保留导致其停止的异常!谢谢兄弟,我可能需要时间来理解这一点……对于线程来说,这是一个非常新的概念,因为我在大学里刚开始学习java
/**
* 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 = new Stepper() {
@Override
public void step() throws Exception {
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) {
}
}
}