Last active
August 29, 2015 14:17
-
-
Save stania/d3749d031301bdf48b11 to your computer and use it in GitHub Desktop.
Thread pause/resume technique
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package sandbox; | |
import java.util.Date; | |
import java.util.concurrent.Phaser; | |
import java.util.concurrent.atomic.AtomicBoolean; | |
public class PhaserTest implements Runnable { | |
private static AtomicBoolean paused = new AtomicBoolean(false); | |
private static Phaser p = new Phaser(1); | |
public static void main(String[] args) throws InterruptedException { | |
Thread t = new Thread(new PhaserTest()); | |
t.start(); | |
boolean state = true; | |
while (true) { | |
Thread.sleep(3000); | |
if (state) { | |
System.err.println("pause!");; | |
if (paused.compareAndSet(false, true)) // considering multi-threaded | |
p.register(); | |
} else { | |
System.err.println("resume!");; | |
if (paused.compareAndSet(true, false)) // considering multi-threaded | |
p.arriveAndDeregister(); | |
} | |
state = !state; | |
} | |
} | |
@Override | |
public void run() { | |
while (true) { | |
try { | |
p.arriveAndAwaitAdvance(); // check paused | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
} | |
System.out.println(new Date()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment