Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Concurrent code review

Chris JonesFeb 23 2012 — edited Feb 23 2012
I am trying to learn to how to use multi-threading. I have tried to create a simple Blocking Queue where the producer add "heelo" every second and the consumer prints each item out.

The program does work, just asking for any critism, of how it could be improved from a concurrent point of view.

class Producer implements Runnable{
	MyBlockingQueue queue;
	volatile private boolean cancel;
	public Producer(MyBlockingQueue queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		while(!cancel){
			
			try {
				queue.offer("Heelo");
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("End of prodcuer thread");
		
	}
	public void Cancel(){this.cancel = true;}
}


class Consumer implements Runnable{
	MyBlockingQueue queue;
	volatile private boolean cancel;
	public Consumer(MyBlockingQueue queue){
		this.queue = queue;
	}
	@Override
	public void run() {
		while(!cancel){
			try {
				System.out.println("New Item on queue " +queue.take());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("End of consumer thread");
	}
	
	public void Cancel(){this.cancel = true;}
	
}

class MyBlockingQueue{
	private ArrayList<String> strings = new ArrayList<String>();
	public synchronized void offer(String s){
		strings.add(s);
		this.notifyAll();
	}
	public synchronized String take() throws InterruptedException{
		while(strings.size()==0){
			wait();
		}
		
		String s = strings.get(strings.size()-1);
		strings.remove(strings.size()-1);
		return s;
		
	}
}

class Test{
	public static void main(String[] args) throws InterruptedException{
		//BlockingQueue<String> queue = new ArrayBlockingQueue<String>(5);
		MyBlockingQueue queue = new MyBlockingQueue();
		Consumer c = new Consumer(queue);
		Thread.sleep(1000);
		Producer p = new Producer(queue);
		new Thread(p).start();
		new Thread(c).start();
		Thread.sleep(5000);
		p.Cancel();
		c.Cancel();
		System.out.println("End of main thread");
	}
}
Thanks

Chris
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 22 2012
Added on Feb 23 2012
5 comments
229 views