Gentle Introduction to Threads What Are Threads OS

  • Slides: 7
Download presentation
Gentle Introduction to Threads

Gentle Introduction to Threads

What Are Threads? • O/S gives us the impression of running several processes simultaneously.

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.

Why Is Multithreading Good? • Switching processes requires quite costly overhead of saving process

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).

When We Use Multithread? • Program that never terminates by itself. A typical example

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.

Two Ways to Obtain a Thread • Extend java. lang. Thread class and override

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)

public class Simple. Thread extends Thread { public Simple. Thread(String str) { super(str); }

public class Simple. Thread extends Thread { public Simple. Thread(String str) { super(str); } } public void run() { for (int i = 0; i < 10; i++) { System. out. println(i + " " + get. Name()); try { sleep((long)(Math. random() * 1000)); } catch (Interrupted. Exception e) {} } System. out. println("DONE! " + get. Name()); } public class Two. Threads. Test { public static void main (String[] args) { new Simple. Thread("Jamaica"). start(); new Simple. Thread("Fiji"). start(); } }

0 Jamaica 0 Fiji 1 Jamaica 2 Fiji 3 Jamaica 4 Fiji 5 Jamaica

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