Bài giảng Java 2 - Trần Duy Thanh - MultiThreading

What are Threads?

Interrupting threads

Thread properties

Threads priorities


Callables and Futures

Threads and Swing


pptx55 trang | Chuyên mục: Java | Chia sẻ: dkS00TYs | Ngày: 08/06/2015 | Lượt xem: 1111 | Lượt tải: 3download
Tóm tắt nội dung Bài giảng Java 2 - Trần Duy Thanh - MultiThreading, để xem tài liệu hoàn chỉnh bạn click vào nút "TẢI VỀ" ở trên
ead has become runnable. We can use follow method to set priority of Thread 	void setPriority(int newP) 19 Daemon Thread Two types of threads in Java: User threads: Created by the user Daemon threads: Threads that work in the background providing service to other threads 	 (e.g. – the garbage collector thread) 20 Daemon Thread When user thread exits, JVM checks to find out if any other thread is running. If there are, it will schedule the next thread. If the only executing threads are daemon threads, it exits. We can set a thread to be a Daemon if we do not want the main program to wait until a thread ends. 21 “isAlive()" Method Use to find out whether a specific thread is running or not. “join()" Method Causes the current thread to wait until the thread on which it is called terminates. Allows specifying the maximum amount of time that the program should wait for the particular thread to terminate. It throws InterruptedException if another thread interrupts it. The calling thread waits until the specified thread terminates. 22 Interrupting Thread There is no longer a way to force a thread to terminate. The interrupt method can be used to request termination of a thread. Checking one thread is interrupted: 	Thread.currentThread().isInterrupted()  If a thread is blocked, it cannot check the interrupted status. This is where the InterruptedException comes in. 23 Interrupting Thread public void run() { try{	. . . 	while (more work to do){ 	do more work 	} } catch(InterruptedException exception){ // thread was interrupted during sleep or wait } finally{ cleanup, if required } // exit run method and terminate thread } Pattern for interrupting an thread 24 Thread Synchronization What happens if two threads have access to the same object and each calls a method that modifies the state of the object? In such a case, data may become inconsistent. Situation is often called a race condition. To avoid simultaneous access of a shared object by multiple threads, you must learn how to synchronize the access. 25 Thread Synchronization - 1st approach Thread Communication Without Synchronization View follow example: UnsynchBankTest.java There are some things wrong in this Bank. The Race Condition Explained: The problem is that these are not atomic operations. View follow figure : p.51 The real problem is that the work of the transfer method can be interrupted in the middle. If we could ensure that the method runs to completion before the thread loses control, then the state of the bank account object would not be corrupted. 26 Thread Synchronization - 1st approach 27 Thread Synchronization - 1st approach Synchronization is based on the concept of monitor. A monitor is an object that is used as a mutually exclusive lock. Only one thread can enter a monitor: When one thread enters the monitor, it means that the thread has acquired a lock All other threads must wait till that thread exits the monitor. For a thread to enter the monitor of an object: The programmer may invoke a method created using the synchronized keyword (implicit synchronize). Or using explicit lock objects. 28 Thread Synchronization - 1st approach Concurrency mechanism: Simply tag any operation that should not be interrupted as synchronized, for example : public synchronized void transfer 	(int from, int to,int amount) When one thread calls a synchronized method, it is guaranteed that the method will finish before another thread can execute any synchronized method on the same object. 29 Thread Synchronization - 1st approach 30 Thread Synchronization - 1st approach When a thread calls a synchronized method, the object becomes "locked." Periodically, the thread scheduler activates the threads that are waiting for the lock to open. Other threads are still free to call unsynchronized methods on a locked object. When a thread leaves a synchronized method by throwing an exception, it still relinquishes the object lock. 31 Thread Synchronization - 1st approach If a thread owns the lock of an object and it calls another synchronized method of the same object, then that method is automatically granted access. The thread only relinquishes the lock when it exits the last synchronized method. 32 Thread Synchronization - 1st approach This mechanism ensures that there is a smooth transition of a particular resource between two competitive threads. It also oversees the condition in a program where one thread is: Allowed to wait for the lock. Notified to end its waiting state and get the lock When a thread executes a call to wait, it surrenders the object lock and enters a wait list for that object. To remove a thread from the wait list, some other thread must make a call to notifyAll or notify, on the same object. 33 Thread Synchronization - 1st approach Java Simplified / Session 16 / 33 of 32 notify() wakes up or notifies the first thread. notify() First thread notifyAll() wakes up or notifies all the threads that called wait( ) on the same object. Thread 1 Thread 2 Thread 3 notifyAll() 34 Thread Synchronization - 1st approach Syntax : synchronized (object){ 	//do your work } Example : public void run(){ try { while (true) { synchronized (bank) { 	//do your work } } } catch (InterruptedException e) {} } 35 Thread Synchronization - 1st approach If one thread calls a synchronized static method of a class, all synchronized static methods of the class are blocked until the first call returns. Example :public static synchronized getInstance() 36 Thread Synchronization – 2nd approach The basic outline for protecting a code block with a ReentrantLock is: private Lock bankLock; private Condition sufficientFunds; bankLock = new ReentrantLock(); sufficientFunds = bankLock.newCondition(); bankLock.lock(); try { while (accounts[from] = amount) 	bank.transfer(from, to, amount); It is entirely possible that the current thread will be deactivated between the successful outcome of the test and the call to transfer:	if (bank.getBalance(from) >= amount) 	// thread might be deactivated at this point 	bank.transfer(from, to, amount); By the time the thread is running again, the account balance may have fallen below the withdrawal amount. Condition Objects 39 Thread Synchronization – 2nd approach Condition Objects 40 Thread Synchronization – 2nd approach Condition Objects What do we do when there is not enough money in the account? We wait until some other thread has added funds. But this thread has just gained exclusive access to the bankLock, so no other thread has a chance to make a deposit. The solution is : condition objects A lock object can have one or more associated condition objects. 41 Thread Synchronization – 2nd approach Condition Objects 42 Thread Synchronization – 2nd approach Condition Objects If the Transfer method finds that sufficient funds are not available, it calls	 =>The current thread is now blocked and gives up the lock. This lets in another thread that can, we hope, increase the account balance 43 Thread Synchronization – 2nd approach Condition Objects There is an essential difference between a thread that is waiting to acquire a lock and a thread that has called await. Once a thread calls the await method, it enters a wait set for that condition. Thread is not unblocked when the lock is available. Instead, it stays blocked until another thread has called the signalAll method on the same condition. 44 Thread Synchronization – 2nd approach Condition Objects The signalAll method call unblocks all threads that are waiting for the condition. When the threads are removed from the wait set, they are again runnable and the scheduler will eventually activate them again. 45 Thread Synchronization – 2nd approach Fainess A fair lock favors the thread that has been waiting for the longest time. By default, locks are not required to be fair. You can specify that you want a fair locking policy: Lock fairLock = new ReentrantLock(true); Fair locks are a lot slower than regular locks. You should only enable fair locking if you have a specific reason why fairness is essential for your problem. 46 Thread Synchronization – 2nd approach Fainess The tryLock method tries to acquire a lock and returns true if it was successful. Otherwise, it immediately returns false. You can call tryLock with a timeout parameter, like this: if(myLock.tryLock(100, TimeUnit.MILLISECONDS)) TimeUnit is an enumeration with values SECONDS, MILLISECONDS, MICROSECONDS, and NANOSECONDS. 47 Deadlocks Analyzing following situation 48 Deadlocks If all threads in an application are blocked. The system has deadlocked. Unfortunately, there is nothing in the Java programming language to avoid or break these deadlocks. You must design your threads to ensure that a deadlock situation cannot occur. Notify/notifyAll method can unblock thread(s). 49 Callables and Futures A Runnable encapsulates a task that runs asynchronously; you can think of it as an asynchronous method with no parameters and no return value. Drawback of Runnable: Cannot return any type (of run method) No parameters (of run method) Processing exception locally. So, we need another mechanic: Callable The Callable interface is a parameterized type, with a single method call: 50 Callables and Futures 51 Callables and Futures A Future object holds the result of an asynchronous computation. You use a Future object so that you can start a computation, give the result to someone, and forget about it. The owner of the Future object can obtain the result when it is ready. 52 Callables and Futures The FutureTask wrapper is a convenient mechanism for turning a Callable into both a Future and a Runnable it implements both interfaces. 53 Callables and Futures Thread is a special and interesting property of Java For building a single program to perform more than one task at the same time (multithreading program) Other advanced technique to use multithreading is Callable The best technique to handling multithreading. 54 Threads and Swing 55 Threads and Swing END 56 

File đính kèm:

  • pptx1.MultiThreading.pptx
Tài liệu liên quan