Download presentation
Presentation is loading. Please wait.
1
Lecture 19 Threads CSE 1322 6/6/2019
2
Threads a thread is a program's path of execution.
Most programs written today run as a single thread, causing problems when multiple events or actions need to occur at the same time. For example, a program is not capable of drawing pictures while reading keystrokes. The program must give its full attention to the keyboard input lacking the ability to handle more than one event at a time. The ideal solution to this problem is the seamless execution of two or more sections of a program at the same time. Threads allows us to do this. 6/6/2019
3
Threads Define worker function/method
Easy to make a separate worker (thread) within a larger program: Define worker function/method Create thread and tell it what method to run when it's started Run/start thread 6/6/2019
4
Multithreading Multithreaded applications deliver their potent power by running many threads concurrently within a single program. Multithreading means multiple lines of a single program can be executed at the same time. The operating system is treating the programs as two separate and distinct processes. Worker threads can be used to perform time-consuming or time-critical tasks without tying up the primary thread. For example, worker threads are often used in server applications to fulfill incoming requests without waiting for the previous request to be completed. Makes use of multiple processors/cores if available Share memory within the program (as opposed to processes which are separate) Must coordinate access to shared memory 6/6/2019
5
Multi-threaded Program
start Main Method Module (Main Thread) Thread A Thread B Thread C switching Fig: Block diagram of a Multi-threaded Program 6/6/2019
6
How to Create a thread? By Extending the Thread Class
2) By Implementing the Runnable Interface 6/6/2019
7
How to Create a thread? By Extending the Thread Class
class MyThread extends Thread { public void run() { System.out.println("Inside MyThread"); // } class MainThread { public static void main(String args[]) { MyThread Th = new MyThread(); Th.start(); // Calls run() Method 6/6/2019
8
How to Create a thread? By Implementing the Runnable Interface
class MyThread implements Runnable{ // public void run() { System.out.println("Inside MyThread"); // } class MainThread { public static void main(String args[]){ MyThread MyObj = new MyThread(); Thread Th = new Thread(MyObj); Th.start(); // Calls run() Method 6/6/2019
9
A simple java threaded program
public class ThreadDemoMain { public static void main (String [] args) MyThread mt = new MyThread (); mt.start (); for (int i = 0; i < 50; i++) System.out.println ("i = " + i + ", i * i = " + i * i); } class MyThread extends Thread { public void run () for (int count = 1, row = 1; row < 20; row++, count++) for (int i = 0; i < count; i++) System.out.print ('*'); System.out.print ('\n'); } 6/6/2019
10
Threads There is a problem with this, though, in that the method that the thread runs does not take in any parameters. To solve this, use a class: Define a class that takes in any needed parameters in its constructor Store the values into object-level attributes The last thing the constructor does is create a thread and run it (invoking an internal method of the class) This worker thread then has access to all the attributes 6/6/2019
11
Using constructors class Demo {
public static void main (String [] args) FinTrans ft = new FinTrans (); TransThread tt1 = new TransThread (ft, "Deposit Thread"); TransThread tt2 = new TransThread (ft, "Withdrawal Thread"); tt1.start (); tt2.start (); } class FinTrans { public static String transName; public static double amount; } class TransThread extends Thread private FinTrans ft; TransThread (FinTrans ft, String name) super (name); this.ft = ft; // Save reference to financial transaction object public void run () . . . 6/6/2019
12
Figure: A thread’s Life Cycle
Thread Life Cycle Newborn State Runnable State Running State Blocked State Dead State Stop Start New Thread Killed Thread Idle Thread (Not Runnable) sleep, wait suspend resume notify Runnable Running Newborn yield Blocked Dead Active Thread Figure: A thread’s Life Cycle 6/6/2019
13
Thread Control Methods
Method Signature Description String getName() Retrieves the name of running thread in the current context in String format void start() This method will start a new thread of execution by calling run() method of Thread/runnable object. void run() This method is the entry point of the thread. Execution of thread starts from this method. void sleep(int sleeptime) This method suspend the thread for mentioned time duration in argument (sleeptime in ms) void yield() By invoking this method the current thread pause its execution temporarily and allow other threads to execute. void join() This method used to queue up a thread in execution. Once called on thread, current thread will wait till calling thread completes its execution boolean isAlive() This method will check if thread is alive or dead Source: 6/6/2019
14
Thread Synchronization
Source: 6/6/2019
15
Synchronized Threads The previous code sample will produce inconsistent output. On a single-processor machine, threads share the processor. As a result, one thread can only execute for a certain time period. On a multiprocessor machine, depending on the number of threads and processors, each thread can have its own processor. On a single-processor machine, a thread's execution period might not last long enough for that thread to finish executing its critical code section before another thread begins executing its own critical code section. On a multiprocessor machine, threads can simultaneously execute code in their critical code sections. However, they might enter their critical code sections at different times. 6/6/2019
16
Synchronized threads' execution orders are unpredictable. There is no guarantee that a thread can complete its critical code section before some other thread enters that section. Hence, we have a race condition, which causes inconsistencies. To prevent race conditions, each thread must complete its critical code section before another thread enters either the same critical code section or another related critical code section that manipulates the same shared variables or resources. Java's synchronized keyword in the context of the synchronized statement and synchronized methods. synchronized (ft) 6/6/2019
17
Simple "Cornflower Blue" XNA Game
6/6/2019
18
After adding worker threads to the game
6/6/2019
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.