© 2002 by Ashby M. Woolf Revision 3 Java Threads Teaching your programs to walk and chew gum at the same time.

Slides:



Advertisements
Similar presentations
1 Multithreaded Programming in Java. 2 Agenda Introduction Thread Applications Defining Threads Java Threads and States Examples.
Advertisements

CS 5704 Fall 00 1 Monitors in Java Model and Examples.
CS4273: Distributed System Technologies and Programming I Lecture 4: Java Threads and Multithread Programming.
Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
22-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Synchronization in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.
28-Jun-15 Producer-Consumer An example of using Threads.
Definitions Process – An executing program
29-Jun-15 Threads and Multithreading. 2 Multiprocessing Modern operating systems are multiprocessing Appear to do more than one thing at a time Three.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Java Threads CS Introduction to Operating Systems.
Threads II. Review A thread is a single flow of control through a program Java is multithreaded—several threads may be executing “simultaneously” If you.
© Amir Kirsh Threads Written by Amir Kirsh. 2 Lesson’s Objectives By the end of this lesson you will: Be familiar with the Java threads syntax and API.
Multithreading.
Lecture 4 : JAVA Thread Programming
Object Oriented Programming Lecture 8: Introduction to laboratorial exercise – part II, Introduction to GUI frames in Netbeans, Introduction to threads.
Threads. Java Threads A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Threads Concurrency in Java. What is mult-tasking? Doing more than one task.
Computer Engineering Rabie A. Ramadan Lecture 8. Agenda 2 Introduction Thread Applications Defining Threads Java Threads and States Priorities Accessing.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
1 Web Based Programming Section 8 James King 12 August 2003.
Threading Eriq Muhammad Adams J
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
15.1 Threads and Multi- threading Understanding threads and multi-threading In general, modern computers perform one task at a time It is often.
Multi-Threading in Java
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads. Objectives You must be able to answer the following questions –What code does a thread execute? –What states can a thread be in? –How does a.
Comunication&Synchronization threads 1 Programación Concurrente Benemérita Universidad Autónoma de Puebla Facultad de Ciencias de la Computación Comunicación.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Java Threads Lilin Zhong. Java Threads 1. New threads 2. Threads in the running state 3. Sleeping threads and interruptions 4. Concurrent access problems.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Java Thread Programming
SCJP 9/10 Threads.
Java Multithreading.
Lecture 9 Object Oriented Programming Using Java
Threads and Multithreading
Multithreading in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Condition Variables and Producer/Consumer
Condition Variables and Producer/Consumer
Java Based Techhnology
Multithreading.
Threads and Multithreading
Threads and Multithreading
برنامه‌نویسی چندنخی Multi-Thread Programming
Threads and Multithreading
Java Thread.
Computer Science 2 06A-Java Multithreading
Threads and Multithreading
Threads and Multithreading
Lecture 19 Threads CSE /6/2019.
CMSC 202 Threads.
Presentation transcript:

© 2002 by Ashby M. Woolf Revision 3 Java Threads Teaching your programs to walk and chew gum at the same time.

© 2002 by Ashby M. Woolf Revision 3 The Agenda Why Threads? Starting a New Thread Shutting Down a Thread Daemon Threads Avoiding Conflicts Which Thread Is First? Cooperating Threads

© 2002 by Ashby M. Woolf Revision 3 Why Threads? You Expect Programs To Do Many Things At Once –Respond to a Mouse Click –Spell Check Spelling –Print –Do Network Communications –Do I/O Performance Utilize Multiprocessors

© 2002 by Ashby M. Woolf Revision 3 Starting A New Thread Four Variations on Starting a Thread

© 2002 by Ashby M. Woolf Revision 3 Starting a New Thread public void run() { } Write a method with the signature: Put your threads actions in the method's body.

© 2002 by Ashby M. Woolf Revision 3 Starting a New Thread public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } Wrap the run method in a class that implements the Runnable interface.

© 2002 by Ashby M. Woolf Revision 3 Starting a New Thread class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); }

© 2002 by Ashby M. Woolf Revision 3 Starting a New Thread class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } java DoARunnable

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked return; from run() start() I/O Unblocked JVM/OS Decision I/O Blocked Running

© 2002 by Ashby M. Woolf Revision 3 Starting a New Thread class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyThread extends Thread { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyThread extends Thread { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAThread { public static void main(String[] args) { MyThread mt = new MyThread(); Thread t = new Thread(mr); mt.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyThread extends Thread { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAThread { public static void main(String[] args) { MyThread mt = new MyThread(); //Thread t = new Thread(mr); mt.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } java DoAThread

© 2002 by Ashby M. Woolf Revision 3 A Self Starting Thread class MyThread extends Thread { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAThread { public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } Move start(); to the constructor.

© 2002 by Ashby M. Woolf Revision 3 class MyThread extends Thread { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAThread { public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } A Self Starting Thread class MyThread2 extends Thread { MyThread2() { start();} public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAThread2 { public static void main(String[] args) { MyThread2 mt = new MyThread2(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyThread2 extends Thread { MyThread2() { start();} public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAThread2 { public static void main(String[] args) { MyThread2 mt = new MyThread2(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyThread2 extends Thread { MyThread2() { start();} public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAThread2 { public static void main(String[] args) { new MyThread2(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } java DoAThread2

© 2002 by Ashby M. Woolf Revision 3 Self Starting a Runnable class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } Move new Thread and start() to the constructor.

© 2002 by Ashby M. Woolf Revision 3 Self Starting a Runnable class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunnable2 implements Runnable { MyRunnable2() { Thread t new Thread(this); t.start(); } public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable2 { public static void main(String[] args) { MyRunnable2 mr = new MyRunnable2(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunnable2 implements Runnable { MyRunnable2() { Thread t new Thread(this); t.start(); } public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable2 { public static void main(String[] args) { MyRunnable2 mr = new MyRunnable2(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunnable2 implements Runnable { MyRunnable2() { Thread t new Thread(this); t.start(); } public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable2 { public static void main(String[] args) { new MyRunnable2(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } java DoARunnable2

© 2002 by Ashby M. Woolf Revision 3 class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunner implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoRunnables { public static void main(String[] args) { MyRunner mr = new MyRunner(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunner implements Runnable { String text; MyRunner(String s) { text = s; } public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoRunnables { public static void main(String[] args) { MyRunner mr = new MyRunner(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunner implements Runnable { String text; MyRunner(String s) { text = s; } public void run() { for(int i = 0; i < 2000; i++) { System.out.println( text + i ); } public class DoRunnables { public static void main(String[] args) { MyRunner mr = new MyRunner(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunner implements Runnable { String text; MyRunner(String s) { text = s; } public void run() { for(int i = 0; i < 2000; i++) { System.out.println( text + i ); } public class DoRunnables { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyRunner mr = new MyRunner(); Thread t = new Thread(mr); t.start(); } for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunner implements Runnable { String text; MyRunner(String s) { text = s; } public void run() { for(int i = 0; i < 2000; i++) { System.out.println( text + i ); } public class DoRunnables { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyRunner mr = new MyRunner("Runner " + j + ": "); Thread t = new Thread(mr); t.start(); } for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyRunner implements Runnable { String text; MyRunner(String s) { text = s; } public void run() { for(int i = 0; i < 500 ; i++) { System.out.println( text + i ); } public class DoRunnables { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyRunner mr = new MyRunner("Runner " + j + ": "); Thread t = new Thread(mr); t.start(); } for(int i = 0; i < 500 ; i++) { System.out.println("main(): " + i); } class MyRunner implements Runnable { String text; MyRunner(String s) { text = s; } public void run() { for(int i = 0; i < 500 ; i++) { System.out.println( text + i ); } public class DoRunnables { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyRunner mr = new MyRunner("Runner " + j + ": "); Thread t = new Thread(mr); t.start(); } for(int i = 0; i < 500 ; i++) { System.out.println("main(): " + i); } Lots of Threads java DoRunnables

© 2002 by Ashby M. Woolf Revision 3 Which Threads Runs First? Thread Priorities

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked return; from run() start() I/O Unblocked JVM/OS Decision I/O Blocked Running We can set priorities for the JVM.

© 2002 by Ashby M. Woolf Revision 3 class MyRunner implements Runnable { String text; MyRunner(String s) { text = s; } public void run() { for(int i = 0; i < 500 ; i++) { System.out.println( text + i ); } public class DoRunnables { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyRunner mr = new MyRunner("Runner " + j + ": "); Thread t = new Thread(mr); t.start(); } for(int i = 0; i < 500 ; i++) { System.out.println("main(): " + i); } class MyPriority implements Runnable { String text; MyPriority(String s) { text = s; } public void run() { for(int i = 0; i < 500 ; i++) { System.out.println( text + i ); } public class DoPriorities { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyPriority mr = new MyPriority("Runner " + j + ": "); Thread t = new Thread(mr); t.start(); } for(int i = 0; i < 500 ; i++) { System.out.println("main(): " + i); } class MyPriority implements Runnable { String text; MyPriority(String s) { text = s; } public void run() { for(int i = 0; i < 500 ; i++) { System.out.println( text + i ); } public class DoPriorities { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyPriority mr = new MyPriority("Runner " + j + ": "); Thread t = new Thread(mr); t.setPriority(j+1); t.start(); } for(int i = 0; i < 500 ; i++) { System.out.println("main(): " + i); } class MyPriority implements Runnable { String text; MyPriority(String s) { text = s; } public void run() { for(int i = 0; i < 500 ; i++) { System.out.println( text + i ); } public class DoPriorities { public static void main(String[] args) { for(int j = 0; j < 10; j++) { MyPriority mr = new MyPriority("Runner " + j + ": "); Thread t = new Thread(mr); t.setPriority(j+1); t.start(); } for(int i = 0; i < 500 ; i++) { System.out.println("main(): " + i); } java DoPriorities Thread Priority

© 2002 by Ashby M. Woolf Revision 3 How Do I Stop a Thread? Return Watch a Variable and Return Daemon Threads

© 2002 by Ashby M. Woolf Revision 3 How to Stop a Thread Return Watch a Control Variable and Return –Set a Shared Variable –Set a Member Variable with a Method Make a Daemon Thread and Stop the Non-Daemons

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked return; from run() start() I/O Unblocked JVM/OS Decision I/O Blocked Running

© 2002 by Ashby M. Woolf Revision 3 class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyQuitable1 implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAQuit1 { public static void main(String[] args) { MyQuitable1 mq = new MyQuitable1(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyQuitable1 implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoAQuit1 { static boolean go = true; public static void main(String[] args) { MyQuitable1 mq = new MyQuitable1(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } class MyQuitable1 implements Runnable { public void run() { for(int i = 0; DoAQuit1.go ; i++) { System.out.println("run(): " + i); } public class DoAQuit1 { static boolean go = true; public static void main(String[] args) { MyQuitable1 mq = new MyQuitable1(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } class MyQuitable1 implements Runnable { public void run() { for(int i = 0; DoAQuit1.go ; i++) { System.out.println("run(): " + i); } public class DoAQuit1 { static boolean go = true; public static void main(String[] args) { MyQuitable1 mq = new MyQuitable1(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } java DoAQuit1 Watching a Shared Variable

© 2002 by Ashby M. Woolf Revision 3 class MyQuitable1 implements Runnable { public void run() { for(int i = 0; DoAQuit1.go ; i++) { System.out.println("run(): " + i); } public class DoAQuit1 { static boolean go = true; public static void main(String[] args) { MyQuitable1 mq = new MyQuitable1(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } Using a Method to Quit class MyQuitable2 implements Runnable { public void run() { for(int i = 0; DoAQuit2.go ; i++) { System.out.println("run(): " + i); } public class DoAQuit2 { static boolean go = true; public static void main(String[] args) { MyQuitable2 mq = new MyQuitable2(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } class MyQuitable2 implements Runnable { public void run() { for(int i = 0; DoAQuit2.go ; i++) { System.out.println("run(): " + i); } public class DoAQuit2 { static boolean go = true; public static void main(String[] args) { MyQuitable2 mq = new MyQuitable2(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } class MyQuitable2 implements Runnable { boolean go = true; public void run() { for(int i = 0; DoAQuit2.go ; i++) { System.out.println("run(): " + i); } public class DoAQuit2 { public static void main(String[] args) { MyQuitable2 mq = new MyQuitable2(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } class MyQuitable2 implements Runnable { boolean go = true; public void quit() {go = false;} public void run() { for(int i = 0; DoAQuit1.go ; i++) { System.out.println("run(): " + i); } public class DoAQuit2 { public static void main(String[] args) { MyQuitable2 mq = new MyQuitable2(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } class MyQuitable2 implements Runnable { boolean go = true; public void quit() {go = false;} public void run() { for(int i = 0; go ; i++) { System.out.println("run(): " + i); } public class DoAQuit2 { public static void main(String[] args) { MyQuitable2 mq = new MyQuitable2(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) go = false; } class MyQuitable2 implements Runnable { boolean go = true; public void quit() {go = false;} public void run() { for(int i = 0; go ; i++) { System.out.println("run(): " + i); } public class DoAQuit2 { public static void main(String[] args) { MyQuitable2 mq = new MyQuitable2(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) mq.quit(); } class MyQuitable2 implements Runnable { boolean go = true; public void quit() {go = false;} public void run() { for(int i = 0; go ; i++) { System.out.println("run(): " + i); } public class DoAQuit2 { public static void main(String[] args) { MyQuitable2 mq = new MyQuitable2(); Thread t = new Thread(mq); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); if( i == 1000 ) mq.quit(); } java DoAQuit2

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked return; from run() start() I/O Unblocked JVM/OS Decision I/O Blocked Running Lonely Daemons

© 2002 by Ashby M. Woolf Revision 3 class MyRunnable implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoARunnable { public static void main(String[] args) { MyRunnable mr = new MyRunnable(); Thread t = new Thread(mr); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } Daemon Threads class MyDaemon implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoADaemon { public static void main(String[] args) { MyDaemon md = new MyDaemon(); Thread t = new Thread(md); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyDaemon implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run(): " + i); } public class DoADaemon { public static void main(String[] args) { MyDaemon md = new MyDaemon(); Thread t = new Thread(md); t.setDaemon(true); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } class MyDaemon implements Runnable { public void run() { for(int i = 0; true ; i++) { System.out.println("run(): " + i); } public class DoADaemon { public static void main(String[] args) { MyDaemon md = new MyDaemon(); Thread t = new Thread(md); t.setDaemon(true); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i); } java DoADaemon

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked return; from run() start() I/O Unblocked JVM/OS Decision I/O Blocked Running Lonely Daemons destroy() stop()

© 2002 by Ashby M. Woolf Revision 3 Putting a Thread to Sleep Z Z Z Z Z Z Z z z z z z z z z z z z z.....

© 2002 by Ashby M. Woolf Revision 3 Sleep class MySleep implements Runnable { public void run() { for(int i = 0; i < 2000; i++) { System.out.println("run() : " + i ); if(i == 500) { System.out.println("Nap Time"); try {Thread.currentThread().sleep(5000L); }catch(Exception e) { e.printStackTrace(); } } public class DoMySleep { public static void main(String[] args) { MySleep ms = new MySleep(); Thread t = new Thread(ms); t.start(); for(int i = 0; i < 2000; i++) { System.out.println("main(): " + i ); } java DoMySleep

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked Sleep State return; from run() start() I/O Unblocked JVM/OS Decision I/O Blocked Running sleep(ms) Lonely Daemons

© 2002 by Ashby M. Woolf Revision 3 How Do I Avoid Access Conflicts? Synchronize Your Work

© 2002 by Ashby M. Woolf Revision 3 Coordinating Access to Shared Data temp = a; a = b; b = temp; temp = a; a = b; b = temp; class Foo { int a = 1; int b = 2; int temp; void f() { temp = a; a = b; b = temp; } temp = ? a = 1 b = 2 temp = 1 a = 1 b = 2 temp = 1 a = 2 b = 2 temp = 2 a = 2 b = 2

© 2002 by Ashby M. Woolf Revision 3 Simple Swap class Foo { int a = 1; int b = 2; int temp; void f() { temp = a; a = b; b = temp; } class MySwap extends Thread { Foo foo; MySwap(Foo f) { foo = f; } public void run() { for(int i = 0; i < ; i++) { foo.f(); } public class DoASwap { public static void main(String[] args) { Foo foo = new Foo(); MySwap ms = new MySwap(foo); ms.start(); for(int i = 0; i < ; i++) { foo.f(); if(foo.a == foo.b) { System.out.print("a:b " + foo.a + ":" + foo.b); System.out.println("\t " + i); } java DoASwap

© 2002 by Ashby M. Woolf Revision 3 Coordinating Access to Shared Values and Objects synchronized ( expression ) { } synchronized ( expression ) { // Code accessing // shared values // and objects } Expression must result in a reference type. Frequently the Object with shared data Locks the lock associated with the object before: Unlocks the lock associated with the object after:

© 2002 by Ashby M. Woolf Revision 3 Coordinating Access to Shared Values and Objects synchronized ( expression ) { // Code accessing // shared values // and objects } "Lock" only applies to other synchronized code.

© 2002 by Ashby M. Woolf Revision 3 class Foo { int a = 1; int b = 2; int temp; void f() { temp = a; a = b; b = temp; } Coordinating Access to Shared Data class Foo { int a = 1; int b = 2; int temp; void f() { synchronized(this) { temp = a; a = b; b = temp; } class Foo { int a = 1; int b = 2; int temp; void f() { synchronized(this) { temp = a; a = b; b = temp; } temp = a; a = b; b = temp; temp = a; a = b; b = temp; Locks this Unlocks this Locks this Unlocks this

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked Object Lock return; from run() start() I/O Unblocked Lock Unavailable Lock Free JVM/OS Decision I/O Blocked Running Lonely Daemons Sleep State sleep(ms)

© 2002 by Ashby M. Woolf Revision 3 class Foo { int a = 1; int b = 2; int temp; void f() { synchronized(this) { temp = a; a = b; b = temp; } class Foo { int a = 1; int b = 2; int temp; synchronized void f() { temp = a; a = b; b = temp; } Synchronized Method Syntax temp = a; a = b; b = temp; temp = a; a = b; b = temp; Locks this Unlocks this Locks this Unlocks this

© 2002 by Ashby M. Woolf Revision 3 class Foo { int a = 1; int b = 2; int temp; void f() { temp = a; a = b; b = temp; } class MySwap extends Thread { Foo foo; MySwap(Foo f) { foo = f; } public void run() { for(int i = 0; i < ; i++) { foo.f(); } public class DoASwap { public static void main(String[] args) { Foo foo = new Foo(); MySwap ms = new MySwap(foo); ms.start(); for(int i = 0; i < ; i++) { foo.f(); if(foo.a == foo.b) { System.out.print("a:b " + foo.a + ":" + foo.b); System.out.println("\t " + i); } class Foo { int a = 1; int b = 2; int temp; synchronized void f() { temp = a; a = b; b = temp; } class MySwap extends Thread { Foo foo; MySwap(Foo f) { foo = f; } public void run() { for(int i = 0; i < ; i++) { foo.f(); } public class DoASwap { public static void main(String[] args) { Foo foo = new Foo(); MySwap ms = new MySwap(foo); ms.start(); for(int i = 0; i < ; i++) { foo.f(); if(foo.a == foo.b) { System.out.print("a:b " + foo.a + ":" + foo.b); System.out.println("\t " + i); } class Foo { int a = 1; int b = 2; int temp; synchronized void f() { temp = a; a = b; b = temp; } class MySwap extends Thread { Foo foo; MySwap(Foo f) { foo = f; } public void run() { for(int i = 0; i < ; i++) { foo.f(); } public class DoASwap { public static void main(String[] args) { Foo foo = new Foo(); MySwap ms = new MySwap(foo); ms.start(); for(int i = 0; i < ; i++) { foo.f(); if( i% == 0 ) { System.out.print("a:b " + foo.a + ":" + foo.b); System.out.println("\t " + i); } Simple Swap 2 java DoASwap2

© 2002 by Ashby M. Woolf Revision 3 Review - Member and Local Variables class Dog { int i; public int cat(int j) { int k = 4; return i + j + k; } j and k are Local i is a Member Variable Local variables don't share.

© 2002 by Ashby M. Woolf Revision 3 How do I Coordinate Threads? The wait() and notify() Methods Can Build Efficient Coordination.

© 2002 by Ashby M. Woolf Revision 3 Got Space? Data Got Data? Producer Consumer Example ProducerConsumer Shared Data SourceCoordinationSink Got Data? Got Space? Data Got Data? put(int i) int get()

© 2002 by Ashby M. Woolf Revision 3 Source - Producer class Source extends Thread { Coordinator c; Source(Coordinator coord) {c = coord;} public void run() { for(int i = 0; i < 500; i++) { c.put(i); System.out.println("put; " + i); try{ sleep( (int)(Math.random()*10) ); } catch(InterruptedException e) {} }

© 2002 by Ashby M. Woolf Revision 3 Sink - Consumer class Sink extends Thread { Coordinator c; Sink(Coordinator coord) {c = coord;} public void run() { for(int i = 0; i < 500; i++) { System.out.println("get: " + c.get()); }

© 2002 by Ashby M. Woolf Revision 3 Coordinator class Coordinator { int data; public void put(int in) { data = in; } public int get() { return data; }

© 2002 by Ashby M. Woolf Revision 3 DoCoordinator public class DoCoordinator { public static void main(String[] args) { Coordinator c = new Coordinator(); Source so = new Source(c); Sink si = new Sink(c); so.start(); si.start(); } java DoCoordinator

© 2002 by Ashby M. Woolf Revision 3 Coordinator class Coordinator2 { int data; public void put(int in) { data = in; } public int get() { return data; } class Coordinator2 { int data; boolean ready = false; public void put(int in) { data = in; } public int get() { return data; } class Coordinator2 { int data; boolean ready = false; public void put(int in) { while( ready ) { wait(); } data = in; } public int get() { return data; } class Coordinator2 { int data; boolean ready = false; public void put(int in) { while( ready ) { try { wait(); } catch(InterruptedException e) {} } data = in; } public int get() { return data; } class Coordinator2 { int data; boolean ready = false; public void put(int in) { while( ready ) { try { wait(); } catch(InterruptedException e) {} } data = in; ready = true; } public int get() { return data; } class Coordinator2 { int data; boolean ready = false; public void put(int in) { while( ready ) { try { wait(); } catch(InterruptedException e) {} } data = in; ready = true; notifyAll() } public int get() { return data; }

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked Sleep State Wait State Object Lock return; from run() start() notify() notifyAll() I/O Unblocked wait() Lock Unavailable Lock Free JVM/OS Decision I/O Blocked Running sleep(ms) Lonely Daemons Releases Locks Keeps Locks

© 2002 by Ashby M. Woolf Revision 3 Coordinator 2 class Coordinator2 { int data; boolean ready = false; public void put(int in) { while( ready ) { try { wait(); } catch(InterruptedException e) {} } data = in; ready = true; notifyAll() } public int get() { return data; } class Coordinator2 { int data; boolean ready = false; public void put(int in) { while( ready ) { try { wait(); } catch(InterruptedException e) {} } data = in; ready = true; notifyAll() } public int get() { while( !ready ) { try( wait(); } catch(InteruptedException e) {} } ready = false; notifyAll(); return data; } class Coordinator2 { int data; boolean ready = false; public synchronized void put(int in) { while( ready ) { try { wait(); } catch(InterruptedException e) {} } data = in; ready = true; notifyAll() } public synchronized int get() { while( !ready ) { try( wait(); } catch(InteruptedException e) {} } ready = false; notifyAll(); return data; } class Coordinator2 { int data; boolean ready = false; public synchronized void put(int in) { while( ready ) { try { wait(); } catch(InterruptedException e) {} } data = in; ready = true; notifyAll() } public synchronized int get() { while( !ready ) { try( wait(); } catch(InteruptedException e) {} } ready = false; notifyAll(); return data; } java DoCoordinator2

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() Suspend State I/O Blocked Sleep State Wait State Object Lock return; from run() start() notify() notifyAll() I/O Unblocked wait() resume() Lock Unavailable Lock Free JVM/OS Decision suspend() I/O Blocked Running sleep(ms) Lonely Daemons

© 2002 by Ashby M. Woolf Revision 3 What is a Good Way to Manage Many Threads? You can Manage Threads with Thread Groups.

© 2002 by Ashby M. Woolf Revision 3 Thread Groups main subgroup1 subgroup3 subgroup2 Thread_c Thread_gThread_f Thread_d Thread_e Thread_bThread_a new Thread(sg1, "Thread_c") sg1 = new ThreadGroup(main, "subgroup1")

© 2002 by Ashby M. Woolf Revision 3 Controlling Thread Groups Collection Management Methods Methods That Operate on the Group Methods that Operate on Threads of a Group Access Restriction Methods

© 2002 by Ashby M. Woolf Revision 3 Summary Starting Threads –Extend Thread –Implement Runnable Priorities Thread States and Transitions

© 2002 by Ashby M. Woolf Revision 3 Blocked Thread States New Runnable Dead new Thread() I/O Blocked Sleep State Wait State Object Lock return; from run() start() notify() notifyAll() I/O Unblocked wait() Lock Unavailable Lock Free JVM/OS Decision I/O Blocked Running sleep(ms) Lonely Daemons

© 2002 by Ashby M. Woolf Revision 3 Summary Starting Threads –Extend Thread –Implement Runnaable Priorities Thread States and Transitions Starting Threads –Extend Thread –Implement Runnaable Priorities Thread States and Transitions Thread Groups

© 2002 by Ashby M. Woolf Revision 3 End of Content