Creating threads
Threads are objects in the Java language. A thread can be defined by extending the java.lang.Thread class or by implementing the java.lang.Runnable interface. The run() method should be overridden and should have the code that will be executed by the new thread. This method must be public with a void return type and should not take any arguments.
Extending thread
If we need to inherit the behavior of the Thread class, we can have a subclass of it. In this case, the disadvantage is that you cannot extend any other class. For instance:
class MyThread extends Thread
{
public void run()
{
System.out.println("Inside run()");
}
}
Now the Thread object can be instantiated and started. Even though the execution method of your thread is called run, you do not call this method directly. Instead, you call the start() method of the thread class. When the start() method is called, the thread moves from the new state to the runnable state. When the Thread Scheduler gives the thread a chance to execute, the run() method will be invoked. If the run() method is called directly, the code in it is executed by the current thread and not by the new thread. For instance:
MyThread mt = new MyThread();
mt.start();
Implementing Runnable
To implement Runnable, you need to define only the run() method:
class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Inside run()");
}
}
Next, create an instance of the class and construct a thread, passing the instance of the class as an argument to the constructor:
MyRunnable mc = new MyRunnable();
Thread t = new Thread(mc);
To start the thread, use the start() method as shown here:
t.start();
Thread constructors
The Thread constructors available are:
- Thread()
- Thread(String name)
- Thread(Runnable runnable)
- Thread(Runnable runnable, String name)
- Thread(ThreadGroup g, Runnable runnable)
- Thread(ThreadGroup g, Runnable runnable, String name)
- Thread(ThreadGroup g, String name)
No comments:
Post a Comment