Break the loop using threads (Threads forum at JavaRanch)
This is an interesting discussion involved Semaphore and Cyclic Barrier in Java. I just keep in here for further references.
- import java.util.concurrent.Semaphore;
- public class PrintUsingSemaphore {
- public static void main(String[] args) throws Exception{
- final Semaphore semaphore = new Semaphore(1);
- class MyPrinter implements Runnable {
- public void run(){
- for (int i = 0; i < 20; i++) {
- try {
- semaphore.acquire();
- System.out.println(i+" "+Thread.currentThread().getName());
- semaphore.release();
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- };
- for (int i = 0; i < 2; i++) {
- Thread t = new Thread(new MyPrinter());
- t.setPriority(Thread.MAX_PRIORITY-i*2);
- t.start();
- }
- Thread.sleep(100000);
- }
- }
- import java.util.concurrent.BrokenBarrierException;
- import java.util.concurrent.CyclicBarrier;
- public class PrintUsingCyclicBarrier {
- public static void main(String[] args) throws Exception{
- final CyclicBarrier semaphore = new CyclicBarrier(2,new Runnable() {
- public void run() {
- System.out.println();
- }
- });
- class MyPrinter implements Runnable {
- public void run(){
- for (int i = 0; i < 20; i++) {
- try {
- semaphore.await();
- System.out.print(i+" ");
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }catch (BrokenBarrierException e) {
- e.printStackTrace();
- }
- }
- }
- };
- for (int i = 0; i < 2; i++) {
- Thread t = new Thread(new MyPrinter());
- t.setPriority(Thread.MAX_PRIORITY-i*2);
- t.start();
- }
- Thread.sleep(100000);
- }
- }
- public static void main(String[] args) throws Exception{
- class MyPrinter implements Runnable {
- public void run(){
- for (int i = 0; i < 20; i++) {
- try {
- System.out.println(i +" "+Thread.currentThread().getName());
- TimeUnit.MILLISECONDS.sleep(1);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- };
- for (int i = 0; i < 2; i++) {
- Thread t = new Thread(new MyPrinter());
- t.start();
- }
- }
No comments:
Post a Comment