Multithreading in Java
Multithreading in Java
What is a Thread?
Think thread of execution or thread of control flow. Java allows a program to have multiple threads running concurrently. What does this mean to us as developers?
Single-Threaded Development
Many programs written for class so far have been single-threaded. When you call a method, it only returns once its task is complete.
Thread Stalling
What happens when a method needs to wait for something before returning, such as user input or a network connection? (Recall accept() from last lecture) How can we handle other tasks while waiting to accept a new network connection?
Multithreading
Answer: Accept connections in a different thread. Java allows us to create new threads for handling concurrent tasks.
How?
Java provides two ways to create a new thread.
Extend the Thread class (java.lang.Thread) Implement the Runnable interface (java.lang.Runnable)
Now What?
To start a new thread, use the inherited method start()
FooThread ft = new FooThread(); ft.start();
Instructing the JVM to create a new thread Call your Thread objects run() method in the new thread
Starting a Runnable
Pass an object that implements Runnable to the constructor of a Thread object, then start the thread as before.
FooRunnable fr = new FooRunnable(); new Thread(fr).start()
Interesting Facts
In many of your Swing programs, main() has consisted of creating a new JFrame object and calling show() on it show() actually starts a new thread that the GUI runs in and returns immediately main() then returns. Why doesnt your program end when main() does? Java applications only exit when all of their threads have stopped.
A Simpler Way
Multithreading can add a lot of complexity to a program. Sometimes you simply want some simple event to happen in the background at a given interval.
Timers
A Timer will internally launch a new thread, but handle most of the work for you. A Timer will call a method when its interval expires.
Timer Guidelines
Timers should be performing quick tasks, such as updating simple state. If a timer is performing a complex operation, its next interval may expire before it finishes, and the timer will become backlogged (bad)
Creating Timers
Java has two Timer classes one located in java.util and one in javax.swing. Well be dealing with the one in the Swing library. Important timer methods:
public Timer(int ms_delay, ActionListener al) public void start() public void stop()
Wait, an ActionListener?
Timers take a delay (in milliseconds) and an ActionListener object in their constructor. Once a timer has started, it will call the ActionListeners ActionPerformed() method each time its interval expires.