When I run the below code which is an example of multithreading using java netbeans compiler my pc hangs.
Why does this happen?
class clicker implements Runnable
{
int click=0;
Thread t;
private volatile boolean runn=true;
public clicker(int p)
{
t=new Thread(this);
t.setPriority(p);
}
public void run()
{
while(runn)
click++;
}
public void stop()
{
runn=false;
}
public void start()
{
t.start();
}
}
public class Hilopri
{
public static void main(String args[])
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
clicker hi=new clicker(Thread.NORM_PRIORITY+2);
clicker low=new clicker(Thread.NORM_PRIORITY-2);
low.start();
hi.start();
try
{
Thread.sleep(500);
}
catch(Exception e)
{
low.stop();
hi.stop();
}
try
{
hi.t.join();
low.t.join();
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Low"+low.click);
System.out.println("High"+hi.click);
}
}
It’s because you call
low.stop()andhi.stop()in the catch block which is only executed ifThread.sleep(500)throws an exception <=> is interrupted. And nothing in your code interrupts it.You probably meant to put the stop calls in a finally block: