I/O Stream, File, Multithreading - Part 1

What threads are, creating them via Thread/Runnable, start() and the thread lifecycle.


Threads let a program run multiple tasks at once; running many threads is multithreading. Thread-based multitasking is lighter and faster than process-based multitasking. A thread is created by extending java.lang.Thread and overriding run(), or by implementing java.lang.Runnable and passing it to Thread; execution begins with start(), which invokes run(). The lifecycle states are New, Running, Suspended, Blocked and Terminated.

Example
class Main extends Thread {
  public void run() {
    System.out.println("Threads are very helpful in java");
  }
}
Code Snippets 5
1. Current thread - name, priority
Basic

1. Current thread - name, priority

// ------------------------------------------------------------------
// 1. Current thread - name, priority
// ------------------------------------------------------------------
package vs.threads;
class CurrentThreadDemo {
  public static void main(String[] args) {
    Thread t = Thread.currentThread();
    System.out.println("CURRENT THREAD = " + t);
    t.setName("NewThread");
    t.setPriority(t.getPriority() - 1);
    System.out.println("CURRENT THREAD = " + t);
    System.out.println("NAME = " + t.getName());
    System.out.println("PRIORITY = " + t.getPriority());
  }
}

2. Creating a thread by extending Thread class
Basic

2. Creating a thread by extending Thread class

package vs.threads;
// 1. Extend the Thread class
class MyThread extends Thread {
  @Override public void run() {
    // Code executed by the new thread
    for(int i = 1; i <= 3; i++) {
      System.out.println("Child Thread: " + i);
      try {
        Thread.sleep(500);
        // Pause briefly to let main thread interleave
      } catch(InterruptedException e) {
        System.out.println("Thread interrupted.");
      }
    }
  }
}
public class ExtendThreadDemo {
  public static void main(String[] args) {
    // 2. Instantiate the thread object
    MyThread t = new MyThread();
    // 3. Start the thread (calls the run() method in a new path of execution)
    t.start();
    // Code executed by the main thread
    for(int i = 1; i <= 3; i++) {
      System.out.println("Main Thread: " + i);
      try {
        Thread.sleep(500);
      } catch(InterruptedException e) {
        System.out.println("Main interrupted.");
      }
    }
  }
}

3. Creating a thread by implementing Runnable
Basic

3. Creating a thread by implementing Runnable

// ------------------------------------------------------------------
// 3. Creating a thread by implementing Runnable
// ------------------------------------------------------------------
package vs.threads;
class ExClass implements Runnable {
  private String name;
  public ExClass(String name) {
    this.name = name;
  }
  @Override public void run() {
    for(int i = 1; i <= 5; i++) {
      System.out.println(name + " : " + i);
      try {
        Thread.sleep(100);
        // suspend for 100 ms
      } catch(InterruptedException e) {
        System.out.println(name + " interrupted");
      }
    }
    System.out.println("EXITING " + name);
  }
}
class RunnableThreadDemo {
  public static void main(String[] args) {
    Thread mt1 = new Thread(new ExClass("ONE"));
    Thread mt2 = new Thread(new ExClass("TWO"));
    Thread mt3 = new Thread(new ExClass("THREE"));
    mt1.start();
    mt2.start();
    mt3.start();
    System.out.println("EXITING MAIN");
  }
}

4. Simple Runnable/Thread basic example (from PPT)
Basic

4. Simple Runnable/Thread basic example (from PPT)

// ------------------------------------------------------------------
// 4. Simple Runnable/Thread basic example (from PPT)
// ------------------------------------------------------------------
package vs.threads;
class Main extends Thread {
  public static void main(String[] args) {
    Main test = new Main();
    test.start();
    // run() starts in new thread
    System.out.println("Threads are very much helpful in java");
  }
  @Override public void run() {
    System.out.println("Threads are very helpful in java");
  }
}

sleep(), wait(), notify(), join(),
Basic

sleep(), wait(), notify(), join(), daemon threads

// ------------------------------------------------------------------
// 5. sleep() - pause the current thread for a given time
// ------------------------------------------------------------------
package vs.threads;
class SleepDemo {
  public static void main(String[] args) {
    System.out.println("Start");
    try {
      Thread.sleep(2000);
      // pause 2 seconds
    } catch(InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("After 2 seconds");
  }
}
// ------------------------------------------------------------------
// 6. yield() - temporarily pause and let other threads run
// ------------------------------------------------------------------
package vs.threads;
class YieldDemo extends Thread {
  public YieldDemo(String name) {
    super(name);
  }
  @Override public void run() {
    for(int i = 0; i < 3; i++) {
      System.out.println(getName() + " running");
      Thread.yield();
      // give others a chance
    }
  }
  public static void main(String[] args) {
    YieldDemo t1 = new YieldDemo("Thread-1");
    YieldDemo t2 = new YieldDemo("Thread-2");
    t1.start();
    t2.start();
  }
}
// ------------------------------------------------------------------
// 7. join() - wait for a thread to finish
// ------------------------------------------------------------------
package vs.threads;
class JoinDemo {
  public static void main(String[] args) throws InterruptedException {
    Thread worker = new Thread(() -> {
      try {
        Thread.sleep(1500); System.out.println("Worker finished");
      } catch(InterruptedException e) {
        e.printStackTrace();
      }
    }
    );
    worker.start();
    worker.join();
    // main waits until worker completes
    System.out.println("Main continues after worker");
  }
}
// ------------------------------------------------------------------
// 8. Thread lifecycle - isAlive
// ------------------------------------------------------------------
package vs.threads;
class LifecycleDemo {
  public static void main(String[] args) throws InterruptedException {
    Thread t = new Thread(() -> {
      try {
        Thread.sleep(500);
      } catch(InterruptedException e) {
        e.printStackTrace();
      }
    }
    );
    System.out.println("State before start: " + t.getState());
    t.start();
    System.out.println("State after start : " + t.getState());
    System.out.println("isAlive           : " + t.isAlive());
    t.join();
    System.out.println("State after join  : " + t.getState());
    System.out.println("isAlive           : " + t.isAlive());
  }
}
// ------------------------------------------------------------------
// 9. Thread priorities
// ------------------------------------------------------------------
package vs.threads;
class PriorityDemo extends Thread {
  PriorityDemo(String name) {
    super(name);
  }
  @Override public void run() {
    System.out.println(getName() + " (priority " + getPriority() + ") running");
  }
  public static void main(String[] args) {
    PriorityDemo low = new PriorityDemo("LOW");
    PriorityDemo high = new PriorityDemo("HIGH");
    low.setPriority(Thread.MIN_PRIORITY);
    // 1
    high.setPriority(Thread.MAX_PRIORITY);
    // 10
    high.start();
    low.start();
    System.out.println("Main priority = " + Thread.currentThread().getPriority());
  }
}
// ------------------------------------------------------------------
// 10. Daemon vs user threads
// ------------------------------------------------------------------
package vs.threads;
class DaemonDemo {
  public static void main(String[] args) {
    Thread daemon = new Thread(() -> {
      while(true) {
        System.out.println("Daemon running in background..."); try {
          Thread.sleep(300);
        } catch(InterruptedException e) {
          break;
        }
      }
    }
    );
    daemon.setDaemon(true);
    // low priority background thread
    daemon.start();
    System.out.println("Main thread doing work...");
    try {
      Thread.sleep(1000);
    } catch(InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("Main finished - JVM exits even though daemon is alive");
  }
}
// ------------------------------------------------------------------
// 11. Synchronization - synchronized method
// ------------------------------------------------------------------
package vs.threads;
class Counter {
  private int count = 0;
  public synchronized void increment() {
    // only one thread at a time
    count++;
  }
  public int getCount() {
    return count;
  }
}
class SyncMethodDemo {
  public static void main(String[] args) throws InterruptedException {
    Counter counter = new Counter();
    Thread t1 = new Thread(() -> {
      for(int i = 0; i < 10000; i++) counter.increment();
    }
    );
    Thread t2 = new Thread(() -> {
      for(int i = 0; i < 10000; i++) counter.increment();
    }
    );
    t1.start();
    t2.start();
    t1.join();
    t2.join();
    System.out.println("Final count = " + counter.getCount());
    // 20000
  }
}
// ------------------------------------------------------------------
// 12. Synchronization - synchronized block
// ------------------------------------------------------------------
package vs.threads;
class Bank {
  private int balance = 1000;
  public void debit(int amount) {
    synchronized(this) {
      // synchronized block on 'this'
      if(amount <= balance) {
        balance -= amount;
        System.out.println(Thread.currentThread().getName() + " debited " + amount + ", balance=" + balance);
      } else {
        System.out.println("Insufficient balance");
      }
    }
  }
}
class SyncBlockDemo {
  public static void main(String[] args) {
    Bank bank = new Bank();
    Runnable r =() -> bank.debit(150);
    new Thread(r, "T1").start();
    new Thread(r, "T2").start();
    new Thread(r, "T3").start();
  }
}
// ------------------------------------------------------------------
// 13. wait() and notify() - thread communication
// ------------------------------------------------------------------
package vs.threads;
class SharedResource {
  private int value;
  private boolean produced = false;
  public synchronized void produce(int v) throws InterruptedException {
    while(produced) {
      wait();
      // wait until consumed
    }
    value = v;
    produced = true;
    System.out.println("Produced " + value);
    notify();
    // wake up consumer
  }
  public synchronized void consume() throws InterruptedException {
    while(! produced) {
      wait();
      // wait until produced
    }
    System.out.println("Consumed " + value);
    produced = false;
    notify();
    // wake up producer
  }
}
class WaitNotifyDemo {
  public static void main(String[] args) {
    SharedResource sr = new SharedResource();
    new Thread(() -> {
      try {
        for(int i = 1; i <= 5; i++) sr.produce(i);
      } catch(InterruptedException e) {
        e.printStackTrace();
      }
    }
    , "Producer").start();
    new Thread(() -> {
      try {
        for(int i = 1; i <= 5; i++) sr.consume();
      } catch(InterruptedException e) {
        e.printStackTrace();
      }
    }
    , "Consumer").start();
  }
}
Video Lesson Open in new tab
Quiz
1. Which of the following is NOT a thread state in Java?
2. How can you create a thread in Java?
3. What does the start() method do?
4. What happens if you call run() instead of start()?
Coding Problems
1. Write a Java program that creates a thread by extending the Thread class, overrides run() to print a message, and starts the thread with start().
Discussion

Login to join the discussion.


No comments yet.