Java Reference
In-Depth Information
thread1.start();
thread2.start();
}
public void run()
{
int pause;
for (int i=0; i<10; i++)
{
try
{
//Use static method currentThread to get
//reference to current thread and then call
//method getName on that reference…
System.out.println(
Thread.currentThread().getName()
+ " being executed.");
pause = (int)(Math.random() * 3000);
//Call static method sleep
Thread.sleep(pause);
}
catch (InterruptedException interruptEx)
{
System.out.println(interruptEx);
}
}
}
}
As another way of implementing the above program, we could declare thread1
and thread2 to be properties of a class that implements the Runnable interface, cre-
ate an object of this class within main and have the constructor for this class create
the threads and start them running. The constructor for each of the Thread objects
still requires a Runnable argument, of course. It is the instance of the surrounding
Runnable class that has been created (identifi ed as this ) that provides this argument,
as shown in the code below.
public class RunnableHelloCount implements Runnable
{
private Thread thread1, thread2;
public static void main(String[] args)
{
RunnableHelloCount threadDemo =
new RunnableHelloCount();
}
Search WWH ::




Custom Search