Advertisements
Home > Java > Java Program to show implement Low & High priority Threads – Q27

Java Program to show implement Low & High priority Threads – Q27

January 14, 2009 Leave a comment Go to comments

Q27: Java Program to create clicker class which sets the priority of two threads (one is having high priority and one is having low priority) and whenever the thread is running it is increasing a counter. In the end print what is the value of the counter for both of the threads.

class clicker implements Runnable{
	int click=0;
	Thread t;
	private volatile boolean running=true;
	
	public clicker(int p){
		t = new Thread(this);
		t.setPriority(p);
	}
	
	public void run(){
		while(running){
			click++;
		}
	}
	
	public void stop(){
		running=false;
	}
	
	public void start(){
		t.start();
	}
}

class HiLoPri{

	public static void main(String args[]){
		Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
		clicker hi = new clicker(Thread.NORM_PRIORITY+2);
		clicker lo = new clicker(Thread.NORM_PRIORITY-2);
		
		lo.start();
		hi.start();
		
		try{
			Thread.sleep(1000);
		}
		catch(InterruptedException e){
			System.out.println("Main thread interrupted.");
		}
		
		lo.stop();
		hi.stop();
		
		try{
			hi.t.join();
			lo.t.join();
		}
		catch(InterruptedException e){
			System.out.println("InterruptedException caught");
		}

		System.out.println("Low-Prioritythread value: " + lo.click);
		System.out.println("High-Prioritythread value: " + hi.click);
	}
}

… from College notes (BCA/MCA assignments):


Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: