170 likes | 188 Views
Learn about threads in Java programming, including thread objects, priorities, scheduling, and examples.
E N D
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. Threads
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? Threads
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 Threads
Example public class CounterThread extends Thread { public void run() { for (int i=0; i<10; i++) System.out.println(“Count: “+I); } public static void main(String args[]) { CounterThread ct = new CounterThread(); ct.start(); } } Threads
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 Threads
Example public class DownCounter implements Runnable { public void run() { for (int i=10; i>0; i--) System.out.println(“Down: “+i); } public static void main(String args[]) { DownCounter ct = new DownCounter(); Thread t = new Thread(ct); t.start(); } } Threads
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 Threads
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 Threads
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 setPriority() (there is also a getPriority() Threads
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 Threads
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!!) Threads
Example public class ResumeExample extends Thread { public void run() { // do something suspend(); resume(); // this line has not effect // do some more stuff } public static void main(String args[]) { ResumeExample rt = new ResumeExample(); rt.start(); rt.resume(); // possible race condition } Threads
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 Threads
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 Threads
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(); }} Threads
Timer import java.util.Date; class Timer implements Runnable { public void run() { while ( true ) { System.out.println( new Date() ); try { Thread.currentThread().sleep(1000); } catch ( InterruptedException e ) {} } } public static void main( String args[] ) { Thread t = new Thread( new Timer() ); t.start(); System.out.println( "Main done" ); } } Threads
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. Threads