Chapter 1 Multithreading

58 164 0
Chapter 1 Multithreading

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 1 Multithreading Lecturer: Hồ Tiến Lâm Contents  Threads Introduction  Interrupting Threads  Thread States  Thread Properties  Synchronization  Synchronization  Callables and Futures 2 GV. Hồ Tiến Lâm Contents  Threads Introduction  Interrupting Threads  Thread States  Thread Properties  Synchronization  Synchronization  Callables and Futures 3 GV. Hồ Tiến Lâm Threads Introduction  Multitasking: the ability to have more than one program working at what seems like the same time.  Programs that can run more than one thread at once are called mutithreaded programs.  What is the difference between multiple processes and multiple threads ? 4 multiple threads ? GV. Hồ Tiến Lâm Threads Introduction (cont.)  Procedure for running a task in a separate thread: 1. Create a class that implements the Runnable interface and put the code for doing task into that class: public interface Runnable { void run() } 5 } class MyRunnable implements Runnable { public void run() { // put task code here } } GV. Hồ Tiến Lâm Threads Introduction (cont.) 2. Create an object of your class: Runnable r = new MyRunnable(); 3. Create a Thread object from the Runnable: Thread t = new Thread(r); 6 4. Start the thread: t.start(); GV. Hồ Tiến Lâm Contents  Threads Introduction  Interrupting Threads  Thread States  Thread Properties  Synchronization  Synchronization  Callables and Futures 7 GV. Hồ Tiến Lâm Interrupting Threads  In JDK 1.0, there was a stop method which is used to terminate another thread. But it's now deprecated.  Use the interrupt method to request termination of a thread.  To check if one thread was interrupted: Thread.currentThread (). isInterrupted () 8 Thread.currentThread (). isInterrupted ()  If a thread is blocked, it cannot check the interrupted status => throws InterruptedException GV. Hồ Tiến Lâm Interrupting Threads (cont.)  public void run() { try { … while (!Thread.currentThread().isInterrupted() && more work to do) { do more work } } catch(InterruptedException e) { // thread was interrupted during sleep or wait 9 // thread was interrupted during sleep or wait } finally { cleanup, if required } // exiting the run method terminates the thread }  The sleep method throws an InterruptedException if you call it when the interrupted status is set. GV. Hồ Tiến Lâm Interrupting Threads (cont.)  public void run() { try { … while (more work to do) { do more work Thread.sleep(delay); } } catch(InterruptedException e) { 10 } catch(InterruptedException e) { // thread was interrupted during sleep or wait } finally { cleanup, if required } // exiting the run method terminates the thread } GV. Hồ Tiến Lâm [...]... Properties Synchronization Callables and Futures GV Hồ Tiến Lâm 17 Thread Priorities In Java, every thread has a priority You can change the priority of any thread with the setPriority method Range of priority: • • • Thread.MIN_PRIORITY: Thread.NORM_PRIORITY: Thread.MAX_PRIORITY: 1 5 10 Thread priorities are highly system dependent GV Hồ Tiến Lâm 18 Thread Priorities (cont.) You should never structure your... remains at $10 0,000 (10 0 accounts x $1, 000) But after a while, the balance changes slightly WHY??? GV Hồ Tiến Lâm 26 The Race Condition Explained Reason: two threads are trying to update an account at the same time Suppose two threads simultaneously carry out the instruction accounts[to] += amount; The problem is that these are not atomic operations The instruction may be processed as follows: 1 2 3 Load... Introduction Interrupting Threads Thread States Thread Properties Synchronization Callables and Futures GV Hồ Tiến Lâm 11 Thread States There are 4 states: • • • • New Runnable Blocked Dead New Threads: • When you create a thread with new operator, the thread is not yet running GV Hồ Tiến Lâm 12 Thread States (cont.) Runnable Threads: • • • When you invoke the start method, the thread is runnable Why is... (time-slicing) GV Hồ Tiến Lâm 13 Thread States (cont.) Blocked Threads: • • • • • The thread goes to sleep by calling the sleep method The thread calls an operation that is blocking on input/output The thread tries to acquire a lock that is currently held by another thread The thread waits for a condition Calls the suspend method of the thread However, this method is deprecated GV Hồ Tiến Lâm 14 Thread States (cont.)... with 10 0 accounts We randomly generate transactions that move money between these accounts Each account has one thread Each transaction moves a random amount of money from the account to another random account The fact: total amount of money in all accounts does NOT change whatever we run program for a long time LET’S SEE THE DEMO! GV Hồ Tiến Lâm 25 An Example of a Race Condition (cont.) Example 1- 3:... Tiến Lâm 15 Thread States (cont.) Dead Threads: • • • • It dies a natural death because the run method exits normally It dies abruptly because an uncaught exception terminates the run method To check if a thread is currently alive (runnable or blocked), use the isAlive method NOTE: You cannot find out if an alive thread is runnable or blocked, or if a runnable thread is running GV Hồ Tiến Lâm 16 Contents... try { critical section } finally { myLock.unlock(); // make sure the lock is unlocked even if an exception is thrown } GV Hồ Tiến Lâm 29 Lock Objects (cont.) See the below timeline: Thread 1 finish executing Thread 1 calls transfer Thread 2 calls transfer→ blocked GV Hồ Tiến Lâm Thread 2 proceed 30 Condition Objects We cannot use code like if (bank.getBalance(from) >= amount) bank.transfer(from, to,... ThreadGroup(groupName); Add a thread to the thread group: Thread t = new Thread(g, threadName); To check whether any threads of a particular group are still runnable, use the activeCount method GV Hồ Tiến Lâm 21 Thread Groups (cont.) To interrupt all threads in a thread group: g.interrupt(); // g: an object of ThreadGroup Thread groups can have child subgroups You can specify the parent group in the constructor,... execute You cause the executing thread to yield by using Thread.yield() If other runnable threads have a priority at least as high as the priority of this thread, they will be scheduled next GV Hồ Tiến Lâm 19 Daemon Threads You can turn a thread into a daemon thread by calling t.setDaemon(true); A daemon is simply a thread that has no other role in life than to serve others GV Hồ Tiến Lâm 20 Thread Groups... (bank.getBalance(from) >= amount) // thread may be deactivated here bank.transfer(from, to, amount); Then the thread is running again, the account balance may have fallen below the withdrawal amount GV Hồ Tiến Lâm 31 Condition Objects (cont.) You must make sure that the thread cannot be interrupted between the test and the insertion: GV Hồ Tiến Lâm 32 Condition Objects (cont.) If there is not enough money in the . Properties  Synchronization  Synchronization  Callables and Futures 11 GV. Hồ Tiến Lâm Thread States  There are 4 states: • New • Runnable • Blocked • Dead New Threads: 12  New Threads: • When you create a thread. method.  Range of priority: • Thread.MIN_PRIORITY: 1 • Thread.NORM_PRIORITY: 5 • Thread.MAX_PRIORITY: 10  Thread priorities are highly system dependent. 18 GV. Hồ Tiến Lâm Thread Priorities (cont.) . for a condition. 14 • The thread waits for a condition. • Calls the suspend method of the thread. However, this method is deprecated. GV. Hồ Tiến Lâm Thread States (cont.) 15 GV. Hồ Tiến Lâm Thread

Ngày đăng: 13/05/2014, 11:00

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan