java | thread priority and volatile use
//Example of Thread priorities
//MIN_PRIORITY=1
//NORMAL_PRIORITY=5
//MAX_PRIORITY=10
class NewThread implements Runnable
{
int click=0;//a local variable of each thread to be incremented
Thread t;
boolean running=true;
NewThread(int p )
{
t=new Thread(this);
t.setPriority(p); //setting priority
}
public void run() //overridden method
{
while(running)
{
click++; //increment of click variable by their thread
}
}
public void stop()//overridden method
{
running=false;
}
}
class ThreadDemo
{
public static void main(String ar[])//main is a thread which start very first
{
// creating three threads
NewThread ob1=new NewThread(10); //highest priority
NewThread ob2=new NewThread(5); //normal priority
NewThread ob3=new NewThread(1); //minimum priority
ob1.t.start();
ob2.t.start();
ob3.t.start();
//waiting for thread to be completed
try{
Thread.sleep(1000);suspending main thread for 1 sec
}
catch(InterruptedException e)
{
System.out.println("Inter");
}
// stoping all threads
ob1.t.stop();
ob2.t.stop();
ob3.t.stop();
try{
System.out.println("Waiting fro threads to be finished");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e)
{
System.out.println("Inter");
}
//output of click variable for each thread
System.out.println("total click of ob1= "+ob1.click);
System.out.println("total click of ob2= "+ob2.click);
System.out.println("total click of ob3= "+ob3.click);
System.out.println("Main Thread Exitting ");
}
}
//volatile: sharing of variable memory between threads.
0 comments:
Post a Comment