Presentation is loading. Please wait.

Presentation is loading. Please wait.

In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.

Similar presentations


Presentation on theme: "In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static."— Presentation transcript:

1 In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static void main method. Two steps are needed to execute a separate thread: 1) an object (inheriting Thread / conforming to Runnable) must be created. 2) the method must be called on the thread object. This invokes a method called run(). Thread.currentThread() is a static method call that will return the thread object associated with current execution Thread.currentThread().sleep(100); Example This statement causes the executing code to be suspended for 100 milliseconds (0.1 sec.) (note: sleep is a static method.)

2 public class Driver { public static void main(String args[]) { MyThread threadA, threadB; threadA = new MyThread(); threadA.start(); threadB = new MyThread(); threadB.start(); runAwhile(); System.out.println("The Driver thread is finished."); } public static void runAwhile() { try { //delay for a random number of millisec. Thread.currentThread().sleep((int)(Math.random()*1000)); } catch (InterruptedException e) {} }

3 public class MyThread extends Thread { public void run() { for (int j=1; j<=5; j++) { System.out.println(Thread.currentThread()+" loop counter:"+j); runAwhile(); } public static void runAwhile() { try { //delay for a random number of millisec. Thread.currentThread().sleep((int)(Math.random()*1000)); } catch (InterruptedException e) {} } The Thread class is the superclass for creating thread objects.

4 public class Driver { public static void main(String args[]) { MyThread threadA, threadB; threadA = new MyThread(); threadA.start(); threadB = new MyThread(); threadB.start(); runAwhile(); System.out.println("The Driver thread is finished."); } public static void runAwhile() { try { //delay for a random number of millisec. Thread.currentThread().sleep((int)(Math.random()*1000)); } catch (InterruptedException e) {} } Thread[Thread-0,5,main] loop counter:1 Thread[Thread-1,5,main] loop counter:1 Thread[Thread-0,5,main] loop counter:2 Thread[Thread-0,5,main] loop counter:3 The Driver thread is finished. Thread[Thread-1,5,main] loop counter:2 Thread[Thread-0,5,main] loop counter:4 Thread[Thread-1,5,main] loop counter:3 Thread[Thread-1,5,main] loop counter:4 Thread[Thread-0,5,main] loop counter:5 Thread[Thread-1,5,main] loop counter:5

5 Suspend a process for the indicated number of milliseconds. sleep (int millisec) - from Thread Initiate the execution of a thread object, concurrent with the executing thread. The new thread executes its run() method. start () - from Thread A thread terminates when its run() method completes execution. Thread termination Suspend the process in the waiting list associated with the object. wait () - from Object Resume one process in the waiting list associated with the object. (Note, this is different than a signal - nothing occurs when no threads are suspended.) notify () - from Object Resume all processes in the waiting list associated with the object. notifyAll () - from Object Causes this thread to allow other threads to execute if they are suspended awaiting the object this thread owns. yield () - from Thread

6 NewRunnableDeadBlocked

7 Every Java object can be locked in one of two ways: When a thread has locked an object, any other thread attempting a lock will be suspended (blocked) until the lock is released. A synchronized instruction forms a critical section. wait, notify and notifyAll can only be called upon a locked object. synchronized(objectRef) { // the objectRef object is locked for the duration of this instruction.... } synchronized returnType someMethod (parmList) { // the this object is locked for the duration of this method call.... } synchronized methods in the same class create a monitor. Calling wait unlocks the object and adds the thread to the object’s wait set.

8 public class LockableObject { private int semaValue; public LockableObject() { semaValue = 0; } public synchronized void lockedWait() { semaValue--; if (semaValue < 0) try { wait(); } catch (InterruptedException e) {} } public synchronized void lockedSignal() { semaValue++; if (semaValue <= 0) notify(); }

9 public class MyThread extends Thread { public LockableObject semaphore = new LockableObject(); public void run() { semaphore.lockedWait(); for (int j=1; j<=5; j++) { System.out.println(Thread.currentThread()+" loop counter:"+j); runAwhile(); } public void runAwhile() {... } } public class Driver { public static void main(String args[]) { MyThread threadA, threadB; threadA = new MyThread(); threadA.start(); threadB = new MyThread(); threadB.start(); System.out.println("The Driver has started other threads."); threadA.semaphore.lockedSignal(); threadB.semaphore.lockedSignal(); try { threadA.join(); threadB.join(); } catch (InterruptedException e) {} System.out.println(“All threads are finished!”); }

10 Producer thread monitorObj.depositData( data ); Consumer thread monitorObj.removeData( data ); public class Monitor { private final int numberOfBuffers = 100; private int buffersInUse = 0; public Monitor() // constructor method { } public synchronized void depositData( int data ) { while (buffersInUse == numberOfBuffers) try { wait(); } catch (InterruptedException e) {} //placeInNextAvailableBuffer(Data); buffersInUse++; notifyAll(); } public synchronized int removeData() { while (buffersInUse == 0) try { wait(); } catch (InterruptedException e) {} //remove data from oldest buffer buffersInUse--; notifyAll(); return dataJustRemoved; }

11 Returns true unless the thread is dead. isAlive () - from Thread Assigns a priority to a thread. Higher numbers mean higher priority to execute. setPriority (int p) - from Thread Sets a thread as a daemon or not. Daemons can continue to run in the background when a program terminates. setDaemon (boolean on) - from Thread suspend (), resume (), stop () - from Thread All are deprecated! deadlock proneunsafe because the thread unlocks all monitors it locked If the thread is blocked via wait or join, then InterruptException is thrown. If the thread is blocked for I/O, then ClosedByInterruptException is thrown. interrupt () - from Thread Causes the executing thread to suspend awaiting the obj thread to die. obj.join () - from Thread


Download ppt "In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static."

Similar presentations


Ads by Google