Arvutiteaduse instituut
  1. Kursused
  2. 2019/20 kevad
  3. Objektorienteeritud programmeerimine (Narva Kolledž) (LTAT.NR.003)
EN
Logi sisse

Objektorienteeritud programmeerimine (Narva Kolledž) 2019/20 kevad

  • Home
  • Materials
  • Grading
  • Java Glossary
  • Cheat sheet (S1-S6)
  • Source Example
  • Links
Chapter 13

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();
  }
}
Chapter 13
  • Arvutiteaduse instituut
  • Loodus- ja täppisteaduste valdkond
  • Tartu Ülikool
Tehniliste probleemide või küsimuste korral kirjuta:

Kursuse sisu ja korralduslike küsimustega pöörduge kursuse korraldajate poole.
Õppematerjalide varalised autoriõigused kuuluvad Tartu Ülikoolile. Õppematerjalide kasutamine on lubatud autoriõiguse seaduses ettenähtud teose vaba kasutamise eesmärkidel ja tingimustel. Õppematerjalide kasutamisel on kasutaja kohustatud viitama õppematerjalide autorile.
Õppematerjalide kasutamine muudel eesmärkidel on lubatud ainult Tartu Ülikooli eelneval kirjalikul nõusolekul.
Courses’i keskkonna kasutustingimused