Download presentation
Presentation is loading. Please wait.
1
Unit 151 Introduction to Threads and Concurrency Introduction to Threads Multithreading Examples Life-cycle of a Thread Thread Priorities More Examples
2
Unit 152 Introduction: What is a Thread? Just like human being can walk, talk, see, hear etc at the same time, computers can also download documents, print a file, receive e-mail concurrently Computers normally achieve concurrency using threads A thread or thread of control is a section of code executed independently of other threads of control within a single program Each thread has its own stack, priority, and virtual set of registers Every program has at least one thread Every Java applet or application is multithreaded
3
Unit 153 Single and Multithreaded Programs
4
Unit 154 Introduction: Where are Threads Used? Threads are used by virtually every computer user in the following instances: – In Internet browsers – In databases –In operating systems (for controlling access to shared resources etc) Benefits of threads –More productivity to the end user (such as responsive user interface) – More efficient use of the computer (such as using the CPU while performing input-output) – Sometimes advantageous to the programmer (such as simplifying program logic)
5
Unit 155 Threads in Java Java is one of the few (the only?) languages that supports threads at the language level Writing multithreaded programs can be tricky: imagine reading three books by reading few words from each book for a few seconds repeatedly in succession Although Java is portable, its multithreading is platform dependent: a multithreaded program could behave differently on different platforms: Under Solaris implementation, an executing thread can run to completion or can be preempted by a higher priority thread On windows (NT and 98) threads are timesliced and preemption occurs with higher as well as with equal priority threads To create a thread, you extend java.lang.Thread or implement java.lang.Runnable
6
Unit 156 Example 1: Extending java.lang.Thread 1 class OurClass1{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass1Tester{ 8 public static void main(String args[]){ 9 OurClass1 oc = new OurClass1(); 10 oc.run(); 11 run(); 12 } 13 static void run(){ 14 for(int i=0; i<100; i++) 15 System.out.print("Shabab."); 16 } 17 } 1 class OurClass2 extends Thread{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass2Tester{ 8 public static void main(String args[]){ 9 OurClass2 oc = new OurClass2(); 10 oc.start(); 11 run(); 12 } 13 static void run(){ 14 for(int i=0; i<100; i++) 15 System.out.print("Shabab."); 16 } 17 }
7
Unit 157 Example 2: Implementing java.lang.Runnable 1 class OurClass3 implements Runnable{ 2 public void run(){ 3 for(int i=0; i<100; i++) 4 System.out.print("Salam "); 5 } 6 } 7 public class OurClass3Tester{ 8 public static void main(String args[]){ 9 OurClass3 oc = new OurClass3(); 10 Thread th = new Thread(oc); 11 th.start(); 12 run(); 13 } 14 static void run(){ 15 for(int i=0; i<100; i++) 16 System.out.print("Shabab."); 17 } 18 }
8
Unit 158 Example 3: Creating Multiple Threads 1 public class SleepingThread extends Thread { 2 private int countDown = 5; 3 private static int threadCount = 0; 4 private int threadNumber = ++threadCount; 5 public SleepingThread() { 6 System.out.println("Making " + getName()); 7 } 8 public void run() { 9 while(true) { 10 try { // don’t wake a sleeping thread before its sleep time expires! 11 System.out.println(getName() + " Executing."); 12 sleep((long)(Math.random()*5000)); 13 }catch(InterruptedException ie){ 14 System.out.println(getName() + " Interrupted."); 15 } 16 if(--countDown == 0) return; 17 } } 18 public static void main(String[] args) { 19 for(int i = 0; i < 5; i++) 20 new SleepingThread().start(); 21 System.out.println("All Threads Started"); 22 }}
9
Unit 159 Threads: Pictorial View of a Lifetime. Thread created new ready running finished blocked start() run() yield(), or time expired stop(), or complete stop() suspend(), sleep(), or wait() stop() resume(), notify(), or notifyAll()
10
Unit 1510 Example 4: A Timer Thread 1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 class TimerThread extends JFrame implements Runnable{ 5 private JTextField jtf = new JTextField(10); 6 private JButton jb = new JButton("Start/Stop"); 7 private int counter = 0; 8 private boolean startStop = true; 9 TimerThread(){ 10 Container cp = getContentPane(); 11 cp.setLayout(new FlowLayout()); 12 cp.add(jtf); 13 cp.add(jb); 14 setSize(200,200); 15 setTitle("A Timer Thread"); 16 show(); 17 jb.addActionListener(new ActionListener(){ 18 public void actionPerformed(ActionEvent ae){ 19 startStop = !startStop; 20 } });}
11
Unit 1511 Example 4: A Timer Thread (cont’d) 21 public void run(){ 22 while (true){ 23 try{ 24 Thread.sleep(1000); 25 }catch(Exception e){} 26 if (startStop) 27 jtf.setText(Integer.toString(counter++)); 28 } 29 } 30 public static void main(String args[]){ 31 new Thread(new TimerThread()).start(); 32 } 33 }
12
Unit 1512 Example 5: A Visitor Thread 1 import java.util.*; 2 public class VisitorThread extends Thread { 3 private Object []array; 4 public VisitorThread(Object array[]) { 5 this.array = array; 6 } 7 public void run() { 8 Integer temp; 9 this.setName("The Visitor"); 10 for(int i = 0; i < array.length; i++){ 11 temp = (Integer)array[i]; 12 array[i] = new Integer (temp.intValue() + i); 13 if(i%3 == 0) Thread.yield(); 14 } 15 System.out.println(getName() + " done!"); 16 } 17 }
13
Unit 1513 Example 5: A Sorter Thread 1 import java.util.*; 2 public class SorterThread extends Thread { 3 private Object []array; 4 public SorterThread(Object array[]){ 5 this.array = array; 6 } 7 public void run() { 8 int minPos = 0; Object temp; 9 for(int i = 0; i < array.length - 1; i++){ 10 minPos = i; 11 if(i%3 == 0) Thread.yield(); 12 for(int k = i + 1; k < array.length; k++){ 13 if(((Integer)array[k]).compareTo(array[minPos]) < 0) 14 minPos = k; 15 } 16 temp = array[minPos]; 17 array[minPos] = array[i]; 18 array[i] = temp; 19 } 20 System.out.println(getName() + " done!"); 21 } 22 }
14
Unit 1514 Example 5: A Tester Thread 1 import java.util.*; 2 public class TesterThread extends Thread { 3 private static Object []array; 4 public TesterThread(int size) { 5 array = new Object[size]; 6 } 7 public static void main(String args[]) { 8 Random r = new Random(); 9 new TesterThread(100); 10 for(int i = 0; i < array.length; i++){ 11 array[i] = new Integer(r.nextInt(100)); 12 } 13 SorterThread sorter = new SorterThread(array); 14 VisitorThread visitor = new VisitorThread(array); 15 sorter.start(); 16 visitor.start(); 17 for(int i = 0; i < array.length; i++){ 18 System.out.println(array[i]); 19 } 20 System.out.println(Thread.currentThread().getName() + " done!"); 21 } 22 }
15
Unit 1515 Threads Priorities As wehave seen, the run( ) methods of the threads in a program will be executed “simultaneously” The programmer can influence the order of threads executions using threads’ priorities Every Java thread has a priority in the range Thread.MIN_PRIORITY (a constant value, 1) and Thread.MAX_PRIORITY (a constant value, 10). The default priority is Thread.NORMAL_PRIORITY (a constant value, 5) Each new thread inherits the priority of the thread that creates it Every thread has a name (including anonymous threads) for identification purposes –More than one thread may have the same name –If a name is not specified when a thread is created, a new name is generated for it
16
Unit 1516 Example 6: Prioritizing the Visitor Thread 1 import java.util.*; 2 public class TesterThread extends Thread { 3 private static Object []array; 4 public TesterThread(int size) { 5 array = new Object[size]; 6 } 7 public static void main(String args[]) { 8 Random r = new Random(); new TesterThread(100); 9 for(int i = 0; i < array.length; i++){ 10 array[i] = new Integer(r.nextInt(100)); 11 } 12 SorterThread sorter = new SorterThread(array); 13 VisitorThread visitor = new VisitorThread(array); 14 sorter.start(); visitor.start(); 15 visitor.setPriority(Thread.MAX_PRIORITY); 16 Thread.currentThread().setPriority(Thread.MIN_PRIORITY); 17 for(int i = 0; i < array.length; i++){ 18 System.out.println(array[i]); 19 } 20 System.out.println(Thread.currentThread().getName() + " done!"); 21 } 22 }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.