Sunday, July 18, 2010

Threads part 1: The basics.

All right, today we will have a look at some really hot stuff - thread creation! This is basic but as many basics is very powerful.

First of all, how to to create a new thread? That's really easy actually. We have 2 ways to do it:

1. We can extend the java.lang.Thread class and override the run() method, like this:
 public class MyThreadClass extends Thread {
public void run() {
System.out.println("This is how we do it!");
}
}

2. We can implement the Runnable interface.
In the Runnable interface the only method that we are supposed to implement is public void run().
 public class MyThreadClass2 implements Runnable {
public void run() {
System.out.println("This is how we do it better!");
}
}

Ok, so far what we have is just a new defined class which has a great potential to be something bigger in our program. Let's instantiate our thread! For the first case that we just considered the only thing to do is:
 MyThreadClass myThreadClass = new MyThreadClass();
Duh...

The second case though will require all 2 lines of code! Here it is:
 MyThreadClass2 r = MyThreadClass2();
Thread t = new Thread(r);

And what we just did is firstly create a runnable object with implemented run() method and then pass it to the Thread class constructor so that our run() will be used when the thread goes into the live!

What we do next is starting a thread!
 t.start();

Nothing more, nothing less. Now we have a new thread alive but as in our lives a lot can happen meanwhile... like for example something that I'm going to do very soon - sleeping. But about this and more I will write in the next part of the article.

No comments:

Post a Comment