Demonstrate threads priorities Assignment Help

Assignment Help: >> Thread Priorities - Demonstrate threads priorities

Demonstrate threads priorities:

class clicker implements runnable {

int c=0;

thread t;

private volatitle

boolean running=true;

public clicker(int p) {

t=new thread(this);

t.setPriority(p);

}

public void run()

{

while(running) {

c++;

}

}

public void stop() running=false;

public void start()

{ t.start();

}

}

class HiLoPri {

public static void main(String a[]) {

Thread.currentThread().setPriority(Thread.MAX_PRIORITY);

clicker h = new clicker(Thread.NORM_PRIORITY+ 2);

clicker l = new clicker(Thread.NORM_PRIORITY-2);

l.start();

h.strat();

try { Thread.sleep(10000);

}

catch(InterruptedException e) {

System.out.println("Main thread interrupted.");

}

l.stop();

h.stop();

// wait for child threads to terminate.

try {

h.t.join();

l.t.join();

}catch(InterruptedException e)

{

System.out.println("InterruptedException caught.");

}

System.out.println("Low-priority thread " + l.c);

System.out.println("high-priority thread " + h.c);

}

}

The output of this program, shown as follows when windows 98 run under the OS, denotes in which the threads did context switch, even by neither voluntarily yielded the CPU nor blocked for I/O. A higher-priority thread got around 90 % of the CPU time.

Low-priority threads: 4408112

High-priority thread: 589626904

Of course, the exact output produced through this program depends on the speed of your CPU and the number of other tasks running in the system. Whenever this similar program is run under a nonpreemtive system, various results will be get, one other note about the preceding program.   Remember that running is preceded through the keyword volatile. While volatile is examined more carefully, it is used here to ensure in which the value of running is examined every time the subsequent loop iterates:

while(running) {

c++;

}

Without the use of volatile, it is free to optimize the loop in such way that the value of running is held in a register of the CPU and not necessarily reexamined with every iteration. The use of volatile avoids this optimization, telling Java which running may modified in ways not directly apparent in the immediate code.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd