Java Threads

Creating a thread class

public class MyThreadClass extends Thread { public void run () { // Your code here } }
  • Just inherit from the Thread class, and override the run function.

Running a thread

MyThreadClass myThread = new MyThreadClass(); myThread.start();
  • Instantiate it like any other object, then call the start method.
  • Threads allow different processes to be run simultaneously so others can perform even while one is delayed.

Delays and interrupts

public class MyThreadClass extends Thread { public void run () { try { Thread.sleep(500); // Your code here (executed after delay) } catch (InterruptedException e) { return; } } }
MyThreadClass myThread = new MyThreadClass(); myThread.start(); myThread.interrupt();
  • The Thread.sleep function will pause the thread for a specified number of milliseconds.
  • With the interrupt there, the delayed action will not be reached.
  • This can be useful for making a background process stop when a user interacts with the main thread.

Challenge

Create 2 threads, make one thread count from 1 to 10 (with a half-second delay after each), make the other thread count by twos from 2 to 20 with a one-second delay between each number. Program the one that finishes first to end the other thread. Run them simultaneously.

Quiz

Completed