// Simple multiple thread demonstration using the Runnable interface
class PriorityThread
{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Thread t = Thread.currentThread();
System.out.println(t);
NewPriority hipri = new NewPriority(Thread.NORM_PRIORITY + 2);
NewPriority lopri =new NewPriority(Thread.NORM_PRIORITY - 2);
lopri.start();
hipri.start();
try
{
Thread.sleep(10000);
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
lopri.stop();
hipri.stop();
try
{
// Instruct main thread to wait for other threads to finish
hipri.rt.join();
lopri.rt.join();
}
catch(InterruptedException e)
{
System.out.println("Interupt exception caught");
}
System.out.println("low priority thread: " + lopri.click);
System.out.println("High priority thread: " + hipri.click);
}
}
class NewPriority implements Runnable //create a new thread class
{
int click = 0;
Thread rt;
private volatile boolean running = true;
NewPriority(int p)
{
rt = new Thread(this);
rt.setPriority(p);
}
// once a thread is started this is the entry point for subsequent time slices
public void run()
{
System.out.println(rt);
while(running)
{
click++;
}
}
public void stop()
{
running=false;
}
public void start()
{
rt.start();
}
}
|