Learning Java/Multithreading
Threads - What they are
[edit | edit source]Threads are a flow of execution. All programs use threads, and you have already constructed a progam that uses a single thread. However, multi threading is more complex. In this section, you will learn why and when to use threads, and, of course, how. The threading concept is pretty easy to understand, and so it should not take too long.
Creating a new Thread
[edit | edit source]If you create a thread, you need to have 2 classes where one is using the other. To take advantage of threads, the two classes must be able to run at exactly the same time. This simultaneous execution is called concurrency.
For example, you have a networked server application with multiple clients. If you use the Input.getUTF() method, the server has to wait until the client has sent data and the method returns. However, no other client can be serviced, even if other clients have sent data, while your program is waiting for the method to return.
Now that you know when to use threads, lets get on with it. There are two ways to make a class use a thread: implementing Runnable or extending Thread. Examples:
class useThread extends Thread class useThread implements Runnable
The rest is the same for both. You will need a method called run. This could run forever. It has no parameters and a return type of void. This is where you put the code that you want to run simultaneously. Note that you only need to create one thread when using 2 tasks! The main thread that is automatically created will continue to run when the other thread is running. To start a thread (ie, get the thread going), use the start() method. Example:
public class UseSomeThread { public static void main(String args[]) { ThisThread prog = new ThisThread(); prog.start(); while(true) { System.out.println("Main Thread"); } } } class ThisThread extends Thread { public void run() { while(true) { System.out.println("This Thread"); } } }
It will print This Thread and Main Thread at the same time. The console should look something like this:
This Thread Main Thread This Thread Main Thread Main Thread This Thread This Thread Main Thread This Thread ...
It won't be exactly even. Now, you know how to multi thread!
Uses in Networking
[edit | edit source]The next section covers networking with multi threading. In this place you will learn the uses.
When creating a chat program, you might want threads - the main thread is the server and the other threads are the client connections. For Example:
class Connection implements Runnable { DataOutputStream out; DataInputStream in; Socket sock; //In contructor, make in, out, and sock with in as sock's input stream and out as sock's output public void run() { try{ in.readUTF(); out.writeUTF("Hello"); } catch ... etc. } }
There are many other programs that will require more than one thread.