Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicLong;

public class Main {
    public static void main(String[] args) throws Exception {
        Runner t = new Runner();
        Thread t1 = new Thread(t);
        for (int i = 0; i < 50; i++) {
            t.queue.add(i);
        }
        System.out.println(("Number of items in queue: " + t.queue.size()));
        t1.start();
        Thread.sleep(1000);
        t1.interrupt();
        t1.join();
        System.out.println(("Number of items in queue: " + t.queue.size()));
        System.out.println(("Joined t1. Finished"));
    }
}

class Runner implements Runnable {
    BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(100);
    AtomicLong m_count = new AtomicLong(0);

    @Override
    public void run() {
        try {
            while (true) {
                queue.take();
                System.out.println("Took item " + m_count.incrementAndGet());
                final long start = System.currentTimeMillis();
                while ((System.currentTimeMillis() - start) < 100) {
                    Thread.yield(); // Spin wait
                }
            }
        } catch (Exception ex) {
            System.out.println("Interrupted. Count: " + m_count.get());
        }
    }
}