Presentation is loading. Please wait.

Presentation is loading. Please wait.

Gentle Introduction to Threads

Similar presentations


Presentation on theme: "Gentle Introduction to Threads"— Presentation transcript:

1 Gentle Introduction to Threads

2 What Are Threads? O/S gives us the impression of running several processes simultaneously. This is achieved by running each process for a few miliseconds, saving its state and switching to the next process. Threads extends this concept from process level to funtion level, running multiple tasks within a process. Threads means control flow. A program with only one thread is not interesting to us because there is nothing new. We are rather interested in multi-threads, which meams multiple control flows within a program.

3 Why Is Multithreading Good?
Switching processes requires quite costly overhead of saving process state (virtual memorymap, interrupt settings, file descriptors, etc.) Switching between threads is relatively cheap. With multithreads, we can achieve the counterintuitive result of running a program faster even on a single processor machine. This is achieved by letting another thread run when one thread is put into sleep(or blocked).

4 When We Use Multithread?
Program that never terminates by itself. A typical example is GUI-based application. Program that spawn many short term tasks. Good example is the server part of client/server. Program that is amenable to parallel processing.

5 Two Ways to Obtain a Thread
Extend java.lang.Thread class and override run(). Class runner extends Thread { public void run() { // your code here } Implement the Runnable interface and use that class as an argument in the Thread constructor. (Will be covered later)

6 public 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((long)(Math.random() * 1000)); } catch (InterruptedException e) {} System.out.println("DONE! " + getName()); public class TwoThreadsTest { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start(); }

7 0 Jamaica 0 Fiji 1 Fiji 1 Jamaica 2 Jamaica 2 Fiji 3 Fiji 3 Jamaica 4 Jamaica 4 Fiji 5 Jamaica 5 Fiji 6 Fiji 6 Jamaica 7 Jamaica 7 Fiji 8 Fiji 9 Fiji 8 Jamaica DONE! Fiji 9 Jamaica DONE! Jamaica


Download ppt "Gentle Introduction to Threads"

Similar presentations


Ads by Google