Session 12 |
Creating tasks and threads
Tasks are objects. To create a task, define a class for the task. The class has to implement
the Runnable
interface. The Runnable
interface is rather simple. All it contains is run
method.Implement this method to tell the system how the thread is going to run. A template for developing a task class is as follows:
// Custom task class public class TaskClass implements Runnable { ... public TaskClass(...) { ... } // Implement the run method of Runnable public void run() { // Tell the system how to run the custom thread ... } ... }
// Client class public class Client { ... public void someMethod() { ... // Create an instance of TaskClass TaskClass task = new TaskClass(...); // Create a thread Thread thread = new Thread(task); // Start a thread thread.start(); ... } ... }
Once TaskClass
is defined, create a task using the constructor. For example,
TaskClass task = new TaskClass(...);
A task must be executed in a thread. The Thread
class contains the constructors for creating threads and many useful methods for controlling threads. To create a thread for a task, use
Thread thread = new Thread(task);
We can then invoke the start()
method to tell the JVM that the thread is ready to run, as
follows:
thread.start();
The JVM will execute the task by invoking the task’s run()
method. When the run()
method completes, the thread terminates.
PS! Pay attention:
The run()
method in a task specifies how to perform the task. This method is automatically invoked by the JVM. You should not invoke it. Invoking run()
directly merely executes this method in the same thread; no new thread is started.
For example, let's look at a program that reads two files at once and then prints their contents line by line. Since both files are processed in parallel, their contents are printed chaotically. If we run the program many times - each time we will get a slightly different output.
Files that can be used as an input
https://raw.githubusercontent.com/mbakhoff/oop-samples/master/threads/countdownlatch.txt
https://raw.githubusercontent.com/mbakhoff/oop-samples/master/threads/executorservice.txt
public class OurFileReader implements Runnable { private String nameOfFile; public OurFileReader(String nameOfFile) { this.nameOfFile= nameOfFile; } @Override public void run() { try (Scanner scanner = new Scanner(new File(nameOfFile))) { while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } } catch (IOException e) { throw new RuntimeException(e); } } } public class Test { public static void main(String[] args) { Thread fileReaderThread1 = new Thread(new OurFileReader("countdownlatch.txt")); Thread fileReaderThread2 = new Thread(new OurFileReader("executorservice.txt")); fileReaderThread1.start(); fileReaderThread2.start(); } }
Session 12 |