java for循环 暂停_java – 更有效的暂停循环方式

本文介绍了一种名为`PauseableThread`的Java类,它允许线程暂停和恢复工作,并展示了ReadWriteLock的使用。通过`Stepper`接口,开发者可以创建可暂停的工作流程,适合处理需要暂停的任务。主要讨论了如何利用这些工具来管理多线程间的同步和控制流程。
摘要由CSDN通过智能技术生成

可用的工具是:

等待/通知 – 我们都试图摆脱这个古老的系统.

信号量 – 一旦你的线程抓住它,你持有它直到释放,所以再次抓住它不会阻止.这意味着您无法在自己的线程中暂停.

CyclicBarrier – 每次使用时都必须重新创建.

ReadWriteLock – 我的最爱.您可以让任意多个线程暂停,并且只有当所有线程都调用了简历时才能恢复.如果你愿意,你甚至可以暂停一下.

import java.util.concurrent.locks.ReadWriteLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**

* 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.

*

* Note that I cannot extend Thread because my resume will clash with Thread's deprecated one.

*

* Usage: Either write a `Stepper` and run it in a `PausableThread` or extend `PausableThread` and call `blockIfPaused()` at appropriate points.

*/

public abstract class PauseableThread implements Runnable {

// The lock.

// We'll hold a read lock on it to pause the thread.

// The thread will momentarily grab a write lock on it to pause.

// This way you can have multiple pausers using normal locks.

private final ReadWriteLock pause = new ReentrantReadWriteLock();

// Flag to cancel the wholeprocess.

private volatile boolean cancelled = false;

// The exception that caused it to finish.

private Exception thrown = null;

@Override

// The core run mechanism.

public void run() {

try {

while (!cancelled) {

// Block here if we're paused.

blockIfPaused();

// Do my work.

step();

}

} catch (Exception ex) {

// Just fall out when exception is thrown.

thrown = ex;

}

}

// 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.

pause.writeLock().lockInterruptibly();

} finally {

// Release the lock immediately to avoid blocking when pause is called.

pause.writeLock().unlock();

}

}

// Pause the work. NB: MUST be balanced by a resume.

public void pause() {

// We can wait for a lock here.

pause.readLock().lock();

}

// Resume the work. NB: MUST be balanced by a pause.

public void resume() {

// Release the lock.

pause.readLock().unlock();

}

// Stop.

public void cancel() {

// Stop everything.

cancelled = true;

}

// start - like a thread.

public void start() {

// Wrap it in a thread.

new Thread(this).start();

}

// Get the exceptuion that was thrown to stop the thread or null if the thread was cancelled.

public Exception getThrown() {

return thrown;

}

// 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 {

private final Stepper stepper;

StepperThread(Stepper stepper) {

this.stepper = stepper;

}

@Override

public void step() throws Exception {

stepper.step();

}

}

// 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(10);

}

};

PauseableThread t = PauseableThread.make(s);

// Start it up.

t.start();

Thread.sleep(1000);

t.pause();

System.out.println("Paused: " + n);

Thread.sleep(1000);

System.out.println("Resuminng: " + n);

t.resume();

Thread.sleep(1000);

t.cancel();

} catch (Exception e) {

}

}

}

编辑:修改代码以更常用.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
暂停恢复歌曲,您可以使用 JLayer 库和 Java 的线程控制。 以下是一个简单的示例代码,演示如何在 Java 中使用 JLayer 暂停恢复歌曲: ```java import java.io.FileInputStream; import javazoom.jl.player.Player; public class MusicPlayer implements Runnable { private Player player; private FileInputStream fis; private boolean isPaused = false; public MusicPlayer(String filePath) { try { fis = new FileInputStream(filePath); player = new Player(fis); } catch (Exception ex) { ex.printStackTrace(); } } public void play() { new Thread(this).start(); } public void pause() { isPaused = true; } public void resume() { isPaused = false; } @Override public void run() { try { while (true) { if (!isPaused) { if (!player.play(1)) { break; } } } } catch (Exception ex) { ex.printStackTrace(); } finally { player.close(); try { fis.close(); } catch (Exception ex) { ex.printStackTrace(); } } } } ``` 在此示例中,我们创建了一个名为 MusicPlayer 的类,该类使用 JLayer 播放音乐。我们使用 FileInputStream 从文件中读取音乐,并使用 Player 类播放音乐。 play() 方法可以启动一个新线程来播放音乐,而 pause() 和 resume() 方法可以暂停恢复播放。 在 run() 方法中,我们使用 while 循环来不断播放音乐。如果 isPaused 为 true,则暂停播放。如果播放结束,则退出循环并关闭播放器和 FileInputStream。 以上就是一个简单的示例代码,演示了如何在 Java 中使用 JLayer 暂停恢复歌曲。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值