Threads A thread is a flow of control

















- Slides: 17

Threads • A thread is a flow of control in a program. • A Java program can use multiple threads of control by having an existing thread start new threads. • The execution of threads is interleaved so that several threads can appear to be running simultaneously. • Threads are given priorities. A high priority thread has preference over a low priority thread. 6/9/2021 Threads 1

Understanding Threads • 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 thread change its state? 6/9/2021 Threads 2

Thread Objects • As is everything else, threads in Java are represented as objects • The code that a thread executes is contains in its run() method • To make a thread eligible for running you call its start() method 6/9/2021 Threads 3

Example public class Counter. Thread extends Thread { public void run() { for (int i=0; i<10; i++) System. out. println(“Count: “+I); } public static void main(String args[]) { Counter. Thread ct = new Counter. Thread(); ct. start(); } } 6/9/2021 Threads 4

Interface Runnable • Classes that implement Runnable can also be run as separate threads • Runnable classes have a run() method • In this case you create a thread specifying the Runnable object as the constructor argument 6/9/2021 Threads 5

Example public class Down. Counter implements Runnable { public void run() { for (int i=10; i>0; i--) System. out. println(“Down: “+i); } public static void main(String args[]) { Down. Counter ct = new Down. Counter(); Thread t = new Thread(ct); t. start(); } } 6/9/2021 Threads 6

When Execution Ends • Your program will run until all of its threads are dead • A thread dies when its run() method returns • You cannot restart a dead thread, but you can access its state and behavior • Threads can be killed prematurely by calling the Threads stop method 6/9/2021 Threads 7

Thread Scheduling • Threads are scheduled like processes • Thread states – – Running Waiting, Sleeping, Suspended, Blocked Ready Dead • When you invoke start(), the Thread is marked ready and placed in the thread queue 6/9/2021 Threads 8

Thread Priorities • Threads can have priorities from 1 to 10 (10 is the highest - this is not Unix) • The default priority is 5 • Priorities can be changed via set. Priority() (there is also a get. Priority() 6/9/2021 Threads 9

Scheduling Implementations • Scheduling is typically either – non-preemptive – preemptive • Most Java implementations use non-preemptive scheduling – Note: I am not sure if this is still true in 1. 2 • This means that a thread leaves the running state only when it is ready to do so 6/9/2021 Threads 10

Leaving the Ready State • A call to the yield() method causes the currently executing thread to go to the ready state (this is done by the thread itself) • suspend() can be used to suspend a thread. It can be called by the thread or another thread • A suspended thread can be resumed via the resume() method (which must be called by another thread!!) 6/9/2021 Threads 11

Example public class Resume. Example extends Thread { public void run() { // do something suspend(); resume(); // this line has not effect // do some more stuff } public static void main(String args[]) { Resume. Example rt = new Resume. Example(); rt. start(); rt. resume(); // possible race condition } 6/9/2021 Threads 12

Sleeping • A sleeping thread suspends itself for a specified period of time and then automatically resumes – public static void sleep(long milliseconds) throws Interrupted Exception • The thread class has an interrupt method that immediately moves a sleeping thread into the ready state. When the thread runs it will see the exception 6/9/2021 Threads 13

Monitors • A monitor controls access to an object • A monitor allows only one thread to be active in the object at a time • A monitor is created for an object with the synchronized keyword • A thread can give up control by calling wait() • Notify is used to return a waiting thread to the object 6/9/2021 Threads 14

Many public class Many extends Thread { private int retry; private String info; public Many (int retry, String info) { this. retry = retry; this. info = info; } public void run () { for (int n = 0; n < retry; ++ n) work(); quit(); } protected void work () { System. out. print(info); } protected void quit () { System. out. print('n'); } public static void main (String args []) { if (args != null) for (int n = 0; n < args. length; ++n) new Many(args. length, args[n]). start(); }} 6/9/2021 Threads 15

Timer import java. util. Date; class Timer implements Runnable { public void run() { while ( true ) { System. out. println( new Date() ); try { Thread. current. Thread(). sleep(1000); } catch ( Interrupted. Exception e ) {} } } public static void main( String args[] ) { Thread t = new Thread( new Timer() ); t. start(); System. out. println( "Main done" ); } } 6/9/2021 Threads 16

Synchronized Methods • Once created, all threads run within the same program and have access to any object a reference can be obtained for. • Each object has a lock that can be held by only one thread at a time. • When a thread executes a call to a method that has been declared as synchronized, it first tries to get the lock for the object the method has been called for. 6/9/2021 Threads 17