1. What is a Thread?

1.1. Definition

  • A thread is a single sequential flow of control within a program.

  • A thread runs within the context of a program's process and takes advantage of the resources allocated for that process and the it's environment.

1.2. Multiple threads

  • Multiple threads can run at the same time in the same process performing different tasks.

  • Multiple threads can share the resources of the process they share.

1.3. Example

class TwoThreadsTest {
   public static void main (String[] args) {
      new SimpleThread("Jamaica").start();
      new SimpleThread("Fiji").start();
   }
}
class SimpleThread extends Thread {
   public SimpleThread(String str) {
      super(str);}
   public void run() {
      for (int i = 0; i < 10; i++) {
         System.out.println(i + " " + getName());
         try {
            sleep((int)(Math.random() * 1000));
         }
         catch (InterruptedException e) {}
      }
      System.out.println("DONE! " + getName());
   }
}

1.3.1. Output

0 Jamaica
0 Fiji
1 Fiji
1 Jamaica
2 Jamaica
2 Fiji
...
8 Fiji
9 Fiji
8 Jamaica
DONE! Fiji
9 Jamaica
DONE! Jamaica

Audio in Portuguese