run()
which gets called by the Thread. Your class will need to have this method. Put your code in this run()
method. Your Runnable class should look similar to:
public class Work implements Runnable{
@Override
public void run() {
//do some work..
}
}
Now, you can create a thread in multiple ways but the most appropriate way is to pass the runnable object in its constructor.Thread thread1 = new Thread(new Work());
Work work = new Work();
Thread thread2 = new Thread(work);
thread1 and thread2 are both valid threads. Now to start a thread, just write:
thread1.start();
thread2.start();
Make sure that you say thread1.start()
and not thread1.run()
. thread1.run()
simply calls the run method within the runnable while thread1.start()
runs the run method in separate thread.Thats it! Now you know the basics of threading in Java!
Watch the video tutorial here:
You missed out the option to extend the thread class to create threads.
ReplyDeleteThats another way to do it. I personally prefer this way as it is much more flexible. :D
Delete