Java s Implementation of Concurrency, and how to use it in our applications.
|
|
- Colin Shepherd
- 6 years ago
- Views:
Transcription
1 Java s Implementation of Concurrency, and how to use it in our applications. 1
2 An application running on a single CPU often appears to perform many tasks at the same time. For example, a streaming audio/video application must perform the following tasks: (R) Read compressed digital audio off the network, and place into Buffer A; (D) Read Buffer A, Decompress it and store in Buffer B; (P) Read Buffer B, and Playback the digital audio; and (U) Update the application s display (i.e., the GUI). When this software runs, it appears that all tasks are being run at the same time, because we cannot perceive when one task starts and another ends. The tasks seem to be running at the same time. Software that can do such things is known as concurrent software. 2
3 On typical systems, the concurrency is perceived. The perceived concurrency is achieved by sequentially running each task on the CPU for a small enough time so that the observer cannot identify which task is currently running. Each task is called a thread of execution, or simply a thread. Thread 1 Application Thread 2 Thread 3 Thread 1... A thread is a unique sequence of statements of an application. Time 3
4 OS and JVM OS Level (higher level) Applications, such as JVM running some program PowerPoint editing a presentation Clock displaying the current time File manager displaying files Run under and are controlled by the OS. OS Level of Concurrency JVM Level of Concurrency JVM Level (lower level) The threads of your application run under and are controlled by the JVM. We will discuss this level of concurrency. We will create threads for our Java application, and get the JVM to Time Division Multiplex (TDM) them. 4
5 Time Division Multiplexing (TDM) Consider a streaming audio application running under the JVM. Assume you have split the application into 4 tasks (RDPU). Assume also you have arranged that the JVM will run these tasks as threads in a round robin fashion. 1. At the end of each time-slice, e.g., 1 millisecond, the JVM 2. Stops the current thread (task) from running, and stores the thread s state to memory. 3. Retrieves the next thread s current state, and starts the thread. Goto step (1). Threads share the CPU in a time-sliced fashion. If a thread completes its task, the JVM removes the thread from the list of threads to run. R D P U R D CPU Time (ms) 5
6 Java s Implementation of Concurrency 2 Main Components: Java s Thread Class and Runnable Interface, and JVM s Thread Queue JVM Thread Objects run Queue T0:YourApp «interface» Runnable main() T1:Thread run() run() T2:Thread Thread run() start() run(). Tn:Thread Java API Java Runtime Environment run() 6
7 Java s Implementation of Concurrency Basic Structure Java provides a Runnable interface and a Thread class, so that you can access and use its threading capability in your application. To access the threading capability, you must implement the run method of Java s Runnable interface. Java s Thread class implements the run method, but it does not do anything, i.e., the method has an empty body. If an application (such as yours) wants to create a concurrent thread, you need to override the run method of the Thread class, and put your code that is to be run as a thread in your overriding run method. 7
8 Java s Implementation of Concurrency Basic Structure Once you have put the code you want to run as a thread in a run method, and you have arranged that your run method overrides the run method of the Thread class, then you can use the start method to start your thread. The start method will add a reference to the run() method of your Thread object to the Thread Queue. The JVM executes the run methods in the queue using TDM in a round robin fashion (other priority schemes are allowed). The main method of an application is automatically entered in the queue, and it is the first thread to run in the round-robin queue. 8
9 Two Ways to Create Threads There are two ways (approaches) you can use to create threads: 1. Extend the Java Thread class, and override the run method. 2. Implement Java s Runnable Interface, and provide a concrete implementation of the run method In either case, you put the code you want to run as a concurrent thread in the run() method. 9
10 Approach 1: Subclass of Thread Create a subclass that extends the Java Thread class In your subclass, define a method named run(). Put the code that you want to run as a thread in the run method of your subclass. Note: your subclass may have other methods, such as set and get methods, as usual. Your run method overrides Java s Thread s run method. Instantiate your subclass, thus creating a Thread object. Invoke the start method of the Thread object. The start method enters a reference to your run method of your Thread object into the Thread Objects run Queue for execution. 10
11 Approach 1: Subclass of Thread Described in UML Class Diagram «interface» Runnable run() JVM Thread Objects run Queue main() Thread Provided by Java MC:MyClass run() run() start() run() MyClass run() get() set() Your Class run().. 11
12 Example of Subclass Approach public class HelloThread extends Thread { public void run() { System.out.println( Hello from a thread! ); public static void main(string args[]) { (new HelloThread()).start(); 12
13 Example of Subclass Approach public class HelloThread extends Thread { The programmer s HelloThread class is a subclass of Java s Thread class. public void run() { System.out.println( Hello from a thread! ); public static void main(string args[]) { (new HelloThread()).start(); 13
14 Example of Subclass Approach public class HelloThread extends Thread { The programmer creates a run() method, that is intended to be run as a thread. public void run() { System.out.println( Hello from a thread! ); public static void main(string args[]) { (new HelloThread()).start(); 14
15 Example of Subclass Approach public class HelloThread extends Thread { public void run() { System.out.println( Hello from a thread! ); public static void main(string args[]) { (new HelloThread()).start(); The programmer creates a Thread object. This object normally will inherit the super class s run() method. However, since this class defines another run() method, it will override the superclass s version. 15
16 Example of Subclass Approach public class HelloThread extends Thread { This run() method overrides the superclass s version. public void run() { System.out.println( Hello from a thread! ); public static void main(string args[]) { (new HelloThread()).start(); 16
17 Example of Subclass Approach public class HelloThread extends Thread { public void run() { System.out.println( Hello from a thread! ); public static void main(string args[]) { (new HelloThread()).start(); The code then starts the Thread by invoking the start() method, which is inherited from the Thread class. 17
18 Example of Subclass Approach public class HelloThread extends Thread { public void run() { System.out.println( Hello from a thread! ); public static void main(string args[]) { (new HelloThread()).start(); The start() method enters a reference to the HelloThread object and the associated run() method into the Thread Queue. 18
19 Approach 2: Implement Runnable Create a class that implements Java s Runnable Interface Define a concrete implementation of the run method in your class. Put the code that you want to run as a thread in the run method of your class Instantiate your class, thus creating a Runnable object. Instantiate a Thread object, passing a reference to your Runnable object to the constructor of the Thread. The constructor will replace the Thread s run method with the run method of your Runnable object that you passed to the constructor. Invoke the start method of the Thread object. References to your Thread object and run method are entered into the Thread Objects run Queue for execution. 19
20 Approach 2: Implement Runnable «interface» Runnable run() JVM Thread Objects run Queue main() MC:MyClass run() Your Class MyClass run() get() set() Thread run() start() run().. run() 20
21 Example 1 of Runnable Approach import java.lang.thread; public class ThreadDemo { public static void main( String[] args ) { ARunnable myrunnable = new ARunnable(); //Create a Runnable Thread t = new Thread(myRunnable); //Create a Thread t.start(); //Place thread object in queue, thus starting it // Let the main thread do other stuff: while(true) System.out.println( Main is running ); class ARunnable implements Runnable { ARunnable() { //Constructor would initialize some fields public void run() { while(true) System.out.println( Thread 2 is running"); 21
22 «interface» Runnable run() JVM Thread Objects run Queue ThreadDemo main() myrunnable: run() ARunnable run() ThreadDemo main() Thread run() start() 22
23 Example 2 of Runnable Approach public class SomeClass { public static void main(string args[]) { new Thread( new Runnable() { public void run() {//put thread s code here. ).start(); 23
24 Example 2 of Runnable Approach public class SomeClass { public static void main(string args[]) { new Thread( Creates a Thread object. new Runnable() { public void run() {//put thread s code here. ).start(); 24
25 Example 2 of Runnable Approach public class SomeClass { public static void main(string args[]) { new Thread( new Runnable() { public void run() {//put thread s code here. ).start(); Specifies the Thread s parameter is of type Runnable. 25
26 Example 2 of Runnable Approach public class SomeClass { public static void main(string args[]) { new Thread( new Runnable() { public void run() {//put thread s code here. ).start(); Normally, you can t instantiate an interface, because an Interface contains abstract methods. For instance, Runnable has an abstract run() method. But, in this case, you are attaching a concrete implementation of the run() method to the object. Thus, when the Runnable object is created, it appears as though the object was created from a class that implements the Runnable interface. This is an example of an anonymous class. 26
27 Example 2 of Runnable Approach public class SomeClass { public static void main(string args[]) { new Thread( new Runnable() { public void run() {//put thread s code here. ).start(); The code then starts the Thread by invoking the start() method of the Thread object. 27
28 Class Diagram of Example 2 Homework 28
29 Example 3 of Runnable Approach public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); public static void main(string[] args) { (new Thread( new HelloRunnable()) ).start(); 29
30 Example 3 of Runnable Approach public class HelloRunnable implements Runnable { Runnable is a Java interface used for implementing threads. It declares an abstract method called run(). public void run() { System.out.println("Hello from a thread!"); public static void main(string[] args) { (new Thread( new HelloRunnable()) ).start(); 30
31 Example 3 of Runnable Approach public class HelloRunnable implements Runnable { The programmer places the code he/she wants to run as a thread into the run() method of a class that implements Runnable. public void run() { System.out.println("Hello from a thread!"); public static void main(string[] args) { (new Thread( new HelloRunnable()) ).start(); 31
32 Example 3 of Runnable Approach public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); public static void main(string[] args) { (new Thread( new HelloRunnable()) ).start(); The programmer creates a Thread object (for example, in the main method) 32
33 Example 3 of Runnable Approach public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); public static void main(string[] args) { (new Thread( new HelloRunnable()) ).start(); A reference to a Runnable object is passed to the Thread s constructor, which replaces the Thread s run() method with the run() method of the runnable object. 33
34 Example 3 of Runnable Approach public class HelloRunnable implements Runnable { This run() method overrides the run()method within the Thread object. public void run() { System.out.println("Hello from a thread!"); public static void main(string[] args) { (new Thread( new HelloRunnable()) ).start(); 34
35 Example 3 of Runnable Approach public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); public static void main(string[] args) { (new Thread( new HelloRunnable()) ).start(); The code then starts the Thread by invoking the start() method of the Thread object. 35
36 Runnable Object vs. Subclass Thread Which of these idioms should you use? The Runnable object approach is more general, because the Runnable object can subclass a class other than Thread. The Thread subclass approach is easier to use in simple applications, but is limited because your class must be a descendant of Thread, and, therefore, cannot be a descendant of another class. 1 st : (new Thread( new HelloRunnable()) ).start(); 2 nd : (new HelloThread()).start(); 36
37 How many threads can a JVM have and the system can maintain perceived concurrency? Plan: create increasing numbers of threads until dragging a window becomes difficult. What is the maximum number of threads that can run concurrently? 37
38 class ARunnable implements Runnable { String threadname = "Initial Dummy Name"; int count = 0; long starttime = 0, stoptime = 0, elapsedtime=0; ARunnable(String threadname) { this.threadname = threadname; starttime = 0; stoptime = 0; elapsedtime = 0; public void run() { starttime = System.nanoTime(); while (true) { if (++count == ) { elapsedtime = System.nanoTime() - starttime; System.out.println(threadName + " " + elapsedtime); break; 38
39 import java.lang.thread; public class ThreadTest { public static void main(string[] args) { int count = 0; ARunnable[] myrunnables = new ARunnable[50000]; Thread[] thread = new Thread[50000]; for (int i = 0; i < 50000; i++) { myrunnables[i] = new ARunnable(Integer.toString(i)); thread[i] = new Thread(myRunnables[i]); thread[i].start(); //Start the Thread while (true) //Main thread if (++count == ) break; 39
40 Note: Declaring Arrays of Objects ARunnable[] myrunnables = new ARunnable[50000]; The above statement creates the array myrunnables which can hold references to 50,000 ARunnable objects. In other words, the MyRunnables variable contains 50,000 memory spaces, each of which can store the address of an ARunnable object. The above statement does not create the ARunnable objects themselves. They have to be created separately using the constructor of the ARunnable class. 40
41 Final Elapsed Time of Each Thread Threads 41
42 SOME METHODS OF THREAD Sleep Interrupt Join Thread static sleep() run() start() interrupt() join() 42
43 THREAD STATIC METHOD: sleep() Pausing Execution with Sleep Thread.sleep(time) causes the current run method to suspend execution for a specified time. Makes more efficient use of the processor For instance: if a thread needs to wait for a certain amount of time before doing something, it is better to invoke sleep than to run a timing loop. void run() { //some tasks to do while (notdone) { for (inti=0; i<waittime; i++); //other tasks to do //No other threads can run during //the for loop. Inefficient void run() { //some tasks to do while (notdone) { Thread.sleep(time); //other tasks to do //This allows other threads to run //during the sleep time. More Efficient 43
44 THREAD INSTANCE METHOD: interrupt() Interrupts Thread objects can be interrupted by other threads (or by themselves). For example: say a mom object needs to wake up a son thread in order to get him to go to work. Code in the mom object would do: son.interrupt(). while (true) { //Portion of the run method of object son try { Thread.sleep(longTime); catch (InterruptedException e) { //mom has interrupted my sleep: Do work now dowork(); // Then go back to sleep :>) 44
45 THREAD INSTANCE METHOD: join() join The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing, and if a current thread invokes: t.join(), then this causes the current thread to pause execution (sleep) until t's thread terminates. 45
46 SYNCHRONIZATION Threads communicate primarily by sharing access to fields and objects. This form of communication is useful, but makes two kinds of errors possible: thread interference and memory consistency errors. Java uses synchronization to prevent these types of problems. 46
47 THREAD INTERFERENCE Interference happens when two operations, running in different threads, but acting on the same data, interleave. Example: consider two threads accessing the shared field, c. Thread A performs c++ : 1. Retrieve the current value of c. 2. Increment the retrieved value by Store the incremented value back in c. Thread B performs c-- : 1. Retrieve the current value of c. 2. Increment the retrieved value by Store the incremented value back in c. Due to the time-slicing nature of thread execution, it is possible that the operations of the two threads will interleave. 47
48 THREAD INTERFERENCE: INTERLEAVING SCENARIO Suppose thread A invokes increment at about the same time thread B invokes decrement. Assume the initial value of c is 0. Due to the time-slicing, a possible scenario is: 1. Thread A: Retrieve c. 2. Thread B: Retrieve c. 3. Thread A: Increment retrieved value; result is Thread B: Decrement retrieved value; result is Thread A: Store result in c; c is now Thread B: Store result in c; c is now -1. Java s synchronization facility can prevent interleaving. 48
49 MEMORY CONSISTENCY ERRORS Memory consistency errors occur when different threads have inconsistent views of what should be the same data. E.g., Suppose Thread A s change action to variable c completes in a non-interleaved manner. At a later time, Thread B reads variable c, but it reads the old value instead of the new value. The causes of memory consistency errors are complex, e.g., Compiler reordering of instructions and data caching. Establishing a happens-before relationship prevents memory consistency errors. Java s synchronization can prevent Memory consistency errors. 49
50 SYNCHRONIZATION: 2 BENEFITS 1. Synchronization establishes a happens-before relationship, and, therefore, prevents memory consistency errors. 2. Synchronization guarantees non-interleaving of operations, and, therefore, prevents thread interference. The Java programming language provides two basic ways to do synchronization: synchronized methods. synchronized statements. 50
51 SYNCHRONIZED METHODS PREVENTING INTERLEAVING public class SynchronizedCounter { private int c = 0; public synchronized void increment() {c++; public synchronized void decrement() {c--; public synchronized int getvalue() {return c; When one thread is executing a synchronized method defined in some object, all other threads that invoke any synchronized method for the same object will block (suspend execution) until the first thread is done with the object. Thus, interleaving is prevented. 51
52 SYNCHRONIZED METHODS PREVENTING MEMORY CONSISTENCY ERRORS public class SynchronizedCounter { private int c = 0; public synchronized void increment() {c++; public synchronized void decrement() {c--; public synchronized int getvalue() {return c; When a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads. 52
53 INTRINSIC LOCKS AND SYNCHRONIZATION Every object has an intrinsic lock associated with it. A thread requiring synchronization has to acquire the object s lock before accessing it, and then release the lock when it s done with accessing the object. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. 53
54 INTRINSIC LOCKS AND SYNCHRONIZATION As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock. When a thread releases an intrinsic lock, a happens-before relationship is established between When the thread releases the lock and Any subsequent acquisition of the same lock. 54
55 SYNCHRONIZATION EXAMPLE Thread 1 Locked A Running Idle Suspended increment() Thread 2 Object A Locked A Running Idle Suspended Locked Unlocked decrement() 55
56 SYNCHRONIZATION EXAMPLE Thread 1 calls the increment() method of Object A, and thus, locks Object A. Thread 1 Locked A Running Idle Suspended increment() Thread 2 Object A Locked A Running Idle Suspended Locked Unlocked decrement() 56
57 SYNCHRONIZATION EXAMPLE Thread 2 attempts to call decrement() on Object A, but it gets blocked, since Object A is locked. Thread 1 Locked A Running Idle Suspended increment() Thread 2 Object A Locked A Running Idle Suspended Locked Unlocked decrement() 57
58 SYNCHRONIZATION EXAMPLE When increment() completes, Thread 1 releases the lock on Object A. Thread 1 Locked A Running Idle Suspended increment() Thread 2 Object A Locked A Running Idle Suspended Locked Unlocked decrement() 58
59 SYNCHRONIZATION EXAMPLE Thread 2 resumes and calls the decrement() method of Object A, and thus, locks Object A. Thread 1 Locked A Running Idle Suspended increment() Thread 2 Object A Locked A Running Idle Suspended Locked Unlocked decrement() 59
60 SYNCHRONIZATION EXAMPLE When Thread 1 is executing the increment() method, the interleaving of the method s operations on field c is impossible because the Object A that contains c is locked. Thread 1 Locked A Running Idle Suspended increment() Thread 2 Object A Locked A Running Idle Suspended Locked Unlocked decrement() 60
61 SYNCHRONIZATION EXAMPLE A Happens-before relationship is established from the time Thread 1 releases the lock on Object A, and the Thread 2 s subsequent lock on Object A, i.e., i happens before j. Thread 1 Locked A Running Idle Suspended increment() i j Thread 2 Object A Locked A Running Idle Suspended Locked Unlocked decrement() 61
62 STATIC SYNCHRONIZED METHODS When a thread invokes a synchronized method, it automatically acquires the intrinsic lock for that method s object and releases it when the method returns. When a static synchronized method is invoked, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to the class s static fields is controlled by a lock that s distinct from the lock for any instance of the class. 62
63 SYNCHRONIZED STATEMENTS Another way to create synchronized code. Intended to prevent a problem called deadlock. public void addname(string name) { synchronized(this) { lastname = name; namecount++; namelist.add(name); Not all code within the method is synchronized, only the code within the braces {. Thus, when the synchronized statement is completed, the lock on the object is released. Compare this to waiting for the code in the entire method to complete, before the lock can be released. 63
64 A concurrent application s execution time not only depends on the time taken to execute T tasks, but it also depends if anyone of the tasks becomes suspended due to locks on objects. A concurrent application s ability to execute in a timely manner is known as its liveness. The most common kind of liveness problems: Deadlock. Starvation and livelock. 64
65 MODELING A NORMAL SCENARIO Thread1 a:classa Thread2 b:classb HOW IT IS SUPPOSED TO WORK c:classf d:classf invoke method m1 on c; thus locking c Print message 5 ms Thread switching time 5 ms return from m1; thus unlocking c invoke m2 on d; thus locking d return from m2; thus unlocking d invoke method m1 on d; thus locking d invoke m2 on c; thus locking c Print message return from m2; thus unlocking c Print message Print message return from m1; thus unlocking d 65
66 MODELING A DEADLOCK SCENARIO Thread1 a:classa Thread2 b:classb c:classf HOW IT CAN GO WRONG d:classf 1 ms invoke method m1 on c; thus locking c Print message 1 ms invoke method m1 on d; thus locking d Print message 1 ms invoke m2 on d T1 is blocked due to T2 s lock on d. invoke m2 on c T2 is blocked due to T1 s lock on c. 1 ms 66
67 STARVATION AND LIVELOCK Starvation Shared resources are made unavailable for long periods by greedy threads. Other threads that also need frequent synchronized access to the same object will often be blocked. Livelock Threads are too busy responding to each other instead of doing useful work. 67
CS 159: Parallel Processing
Outline: Concurrency using Java CS 159: Parallel Processing Spring 2007 Processes vs Threads Thread basics Synchronization Locks Examples Avoiding problems Immutable objects Atomic operations High"level
More informationMultithreaded Programming Part II. CSE 219 Stony Brook University, Department of Computer Science
Multithreaded Programming Part II CSE 219 Stony Brook University, Thread Scheduling In a Java application, main is a thread on its own Once multiple threads are made Runnable the thread scheduler of the
More informationCS 351 Design of Large Programs Threads and Concurrency
CS 351 Design of Large Programs Threads and Concurrency Brooke Chenoweth University of New Mexico Spring 2018 Concurrency in Java Java has basic concurrency support built into the language. Also has high-level
More informationAdvanced Programming Concurrency
Advanced Programming Concurrency Concurrent Programming Until now, a program was a sequence of operations, executing one after another. In a concurrent program, several sequences of operations may execute
More informationCOMP 346 WINTER Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION
COMP 346 WINTER 2018 1 Tutorial 2 SHARED DATA MANIPULATION AND SYNCHRONIZATION REVIEW - MULTITHREADING MODELS 2 Some operating system provide a combined user level thread and Kernel level thread facility.
More informationComputation Abstractions. Processes vs. Threads. So, What Is a Thread? CMSC 433 Programming Language Technologies and Paradigms Spring 2007
CMSC 433 Programming Language Technologies and Paradigms Spring 2007 Threads and Synchronization May 8, 2007 Computation Abstractions t1 t1 t4 t2 t1 t2 t5 t3 p1 p2 p3 p4 CPU 1 CPU 2 A computer Processes
More informationConcurrency in Object Oriented Programs 1. Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter
Concurrency in Object Oriented Programs 1 Object-Oriented Software Development COMP4001 CSE UNSW Sydney Lecturer: John Potter Outline Concurrency: the Future of Computing Java Concurrency Thread Safety
More informationWhat is a thread anyway?
Concurrency in Java What is a thread anyway? Smallest sequence of instructions that can be managed independently by a scheduler There can be multiple threads within a process Threads can execute concurrently
More informationMultitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multit
Threads Multitasking Multitasking allows several activities to occur concurrently on the computer. A distinction is usually made between: Process-based multitasking Thread-based multitasking Multitasking
More informationThreads Chate Patanothai
Threads Chate Patanothai Objectives Knowing thread: 3W1H Create separate threads Control the execution of a thread Communicate between threads Protect shared data C. Patanothai Threads 2 What are threads?
More informationNote: Each loop has 5 iterations in the ThreeLoopTest program.
Lecture 23 Multithreading Introduction Multithreading is the ability to do multiple things at once with in the same application. It provides finer granularity of concurrency. A thread sometimes called
More information7. MULTITHREDED PROGRAMMING
7. MULTITHREDED PROGRAMMING What is thread? A thread is a single sequential flow of control within a program. Thread is a path of the execution in a program. Muti-Threading: Executing more than one thread
More informationPerformance Throughput Utilization of system resources
Concurrency 1. Why concurrent programming?... 2 2. Evolution... 2 3. Definitions... 3 4. Concurrent languages... 5 5. Problems with concurrency... 6 6. Process Interactions... 7 7. Low-level Concurrency
More informationContribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team
http://101companies.org/wiki/ Contribution:javaMultithreading Multithreading Prof. Dr. Ralf Lämmel Universität Koblenz-Landau Software Languages Team Non-101samples available here: https://github.com/101companies/101repo/tree/master/technologies/java_platform/samples/javathreadssamples
More informationCMSC 132: Object-Oriented Programming II. Threads in Java
CMSC 132: Object-Oriented Programming II Threads in Java 1 Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read & write files
More informationCIS233J Java Programming II. Threads
CIS233J Java Programming II Threads Introduction The purpose of this document is to introduce the basic concepts about threads (also know as concurrency.) Definition of a Thread A thread is a single sequential
More informationINF 212 ANALYSIS OF PROG. LANGS CONCURRENCY. Instructors: Crista Lopes Copyright Instructors.
INF 212 ANALYSIS OF PROG. LANGS CONCURRENCY Instructors: Crista Lopes Copyright Instructors. Basics Concurrent Programming More than one thing at a time Examples: Network server handling hundreds of clients
More informationJava Threads. COMP 585 Noteset #2 1
Java Threads The topic of threads overlaps the boundary between software development and operation systems. Words like process, task, and thread may mean different things depending on the author and the
More informationCS 556 Distributed Systems
CS 556 Distributed Systems Tutorial on 4 Oct 2002 Threads A thread is a lightweight process a single sequential flow of execution within a program Threads make possible the implementation of programs that
More informationLe L c e t c ur u e e 7 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Multithreading
Course Name: Advanced Java Lecture 7 Topics to be covered Multithreading Thread--An Introduction Thread A thread is defined as the path of execution of a program. It is a sequence of instructions that
More informationAnimation Part 2: MoveableShape interface & Multithreading
Animation Part 2: MoveableShape interface & Multithreading MoveableShape Interface In the previous example, an image was drawn, then redrawn in another location Since the actions described above can apply
More informationFaculty of Computers & Information Computer Science Department
Cairo University Faculty of Computers & Information Computer Science Department Theoretical Part 1. Introduction to Critical Section Problem Critical section is a segment of code, in which the process
More informationOverview. Processes vs. Threads. Computation Abstractions. CMSC 433, Fall Michael Hicks 1
CMSC 433 Programming Language Technologies and Paradigms Spring 2003 Threads and Synchronization April 1, 2003 Overview What are threads? Thread scheduling, data races, and synchronization Thread mechanisms
More informationRecapitulation of basics. Concurrent Programming in Java. Java Threads. Managing Thread objects. Concurrent Thread Execution. Starting a Thread (1)
Concurrent Programming in Java bhik Roychoudhury CS 3211 National University of Singapore Recapitulation of basics Concurrency concepts Threads / Processes structuring mechanism Different from procedures
More informationObject Oriented Programming. Week 10 Part 1 Threads
Object Oriented Programming Week 10 Part 1 Threads Lecture Concurrency, Multitasking, Process and Threads Thread Priority and State Java Multithreading Extending the Thread Class Defining a Class that
More informationConcurrent Computing CSCI 201 Principles of Software Development
Concurrent Computing CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Threads Multi-Threaded Code CPU Scheduling Program USC CSCI 201L Thread Overview Looking
More informationMultithreading Pearson Education, Inc. All rights reserved.
1 23 Multithreading 2 23.1 Introduction Multithreading Provides application with multiple threads of execution Allows programs to perform tasks concurrently Often requires programmer to synchronize threads
More informationMultithread Computing
Multithread Computing About This Lecture Purpose To learn multithread programming in Java What You Will Learn ¾ Benefits of multithreading ¾ Class Thread and interface Runnable ¾ Thread methods and thread
More informationRecap. Contents. Reenterancy of synchronized. Explicit Locks: ReentrantLock. Reenterancy of synchronise (ctd) Advanced Thread programming.
Lecture 07: Advanced Thread programming Software System Components 2 Behzad Bordbar School of Computer Science, University of Birmingham, UK Recap How to deal with race condition in Java Using synchronised
More informationJava Programming Lecture 23
Java Programming Lecture 23 Alice E. Fischer April 19, 2012 Alice E. Fischer () Java Programming - L23... 1/20 April 19, 2012 1 / 20 Outline 1 Thread Concepts Definition and Purpose 2 Java Threads Creation
More informationThreads. Definitions. Process Creation. Process. Thread Example. Thread. From Volume II
Definitions A glossary Threads From Volume II Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Threads Slide 1 of 30 PMultitasking: (concurrent ramming, multiramming) the illusion of running
More informationUNIT IV MULTITHREADING AND GENERIC PROGRAMMING
UNIT IV MULTITHREADING AND GENERIC PROGRAMMING Differences between multithreading and multitasking, thread life cycle, creating threads, creating threads, synchronizing threads, Inter-thread communication,
More informationCMSC 433 Programming Language Technologies and Paradigms. Concurrency
CMSC 433 Programming Language Technologies and Paradigms Concurrency What is Concurrency? Simple definition Sequential programs have one thread of control Concurrent programs have many Concurrency vs.
More informationUser Space Multithreading. Computer Science, University of Warwick
User Space Multithreading 1 Threads Thread short for thread of execution/control B efore create Global During create Global Data Data Executing Code Code Stack Stack Stack A fter create Global Data Executing
More informationJAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling
JAVA and J2EE UNIT - 4 Multithreaded Programming And Event Handling Multithreaded Programming Topics Multi Threaded Programming What are threads? How to make the classes threadable; Extending threads;
More informationConcurrent Programming using Threads
Concurrent Programming using Threads Threads are a control mechanism that enable you to write concurrent programs. You can think of a thread in an object-oriented language as a special kind of system object
More informationMultiThreading. Object Orientated Programming in Java. Benjamin Kenwright
MultiThreading Object Orientated Programming in Java Benjamin Kenwright Outline Review Essential Java Multithreading Examples Today s Practical Review/Discussion Question Does the following code compile?
More informationOnly one thread can own a specific monitor
Java 5 Notes Threads inherit their priority and daemon properties from their creating threads The method thread.join() blocks and waits until the thread completes running A thread can have a name for identification
More informationThreads and Parallelism in Java
Threads and Parallelism in Java Java is one of the few main stream programming languages to explicitly provide for user-programmed parallelism in the form of threads. A Java programmer may organize a program
More informationJava Threads. Introduction to Java Threads
Java Threads Resources Java Threads by Scott Oaks & Henry Wong (O Reilly) API docs http://download.oracle.com/javase/6/docs/api/ java.lang.thread, java.lang.runnable java.lang.object, java.util.concurrent
More informationMulti-threading in Java. Jeff HUANG
Multi-threading in Java Jeff HUANG Software Engineering Group @HKUST Do you use them? 2 Do u know their internals? 3 Let s see File DB How can they service so many clients simultaneously? l 4 Multi-threading
More informationChair of Software Engineering. Java and C# in depth. Carlo A. Furia, Marco Piccioni, Bertrand Meyer. Java: concurrency
Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: concurrency Outline Java threads thread implementation sleep, interrupt, and join threads that return values Thread synchronization
More informationJava Threads Vs Processes. CS Concurrent Programming. Java Threads. What can a thread do? Java Concurrency
Java Threads Vs Processes CS6868 - Concurrent Programming Java Concurrency V. Krishna Nandivada Typically each instance of JVM creates a single process. Each process creates one or more threads. Main thread
More informationThreads Synchronization
Synchronization Threads Synchronization Threads share memory so communication can be based on shared references. This is a very effective way to communicate but is prone to two types of errors: Interference
More informationOverview. CMSC 330: Organization of Programming Languages. Concurrency. Multiprocessors. Processes vs. Threads. Computation Abstractions
CMSC 330: Organization of Programming Languages Multithreaded Programming Patterns in Java CMSC 330 2 Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to
More informationThreads SPL/2010 SPL/20 1
Threads 1 Today Processes and Scheduling Threads Abstract Object Models Computation Models Java Support for Threads 2 Process vs. Program processes as the basic unit of execution managed by OS OS as any
More informationJava Threads. Written by John Bell for CS 342, Spring 2018
Java Threads Written by John Bell for CS 342, Spring 2018 Based on chapter 9 of Learning Java, Fourth Edition by Niemeyer and Leuck, and other sources. Processes A process is an instance of a running program.
More informationVirtual Machine Design
Virtual Machine Design Lecture 4: Multithreading and Synchronization Antero Taivalsaari September 2003 Session #2026: J2MEPlatform, Connected Limited Device Configuration (CLDC) Lecture Goals Give an overview
More informationObject Oriented Programming (II-Year CSE II-Sem-R09)
(II-Year CSE II-Sem-R09) Unit-VI Prepared By: A.SHARATH KUMAR M.Tech Asst. Professor JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY, HYDERABAD. (Kukatpally, Hyderabad) Multithreading A thread is a single sequential
More informationCOURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE
COURSE 11 PROGRAMMING III OOP. JAVA LANGUAGE PREVIOUS COURSE CONTENT Input/Output Streams Text Files Byte Files RandomAcessFile Exceptions Serialization NIO COURSE CONTENT Threads Threads lifecycle Thread
More informationWeek 7. Concurrent Programming: Thread Synchronization. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Week 7 Concurrent Programming: Thread Synchronization CS 180 Sunil Prabhakar Department of Computer Science Purdue University Announcements Exam 1 tonight 6:30 pm - 7:30 pm MTHW 210 2 Outcomes Understand
More informationIntroduction to Java Threads
Object-Oriented Programming Introduction to Java Threads RIT CS 1 "Concurrent" Execution Here s what could happen when you run this Java program and launch 3 instances on a single CPU architecture. The
More informationCPS221 Lecture: Threads
Objectives CPS221 Lecture: Threads 1. To introduce threads in the context of processes 2. To introduce UML Activity Diagrams last revised 9/5/12 Materials: 1. Diagram showing state of memory for a process
More informationUnit 4. Thread class & Runnable Interface. Inter Thread Communication
Unit 4 Thread class & Runnable Interface. Inter Thread Communication 1 Multithreaded Programming Java provides built-in support for multithreaded programming. A multithreaded program contains two or more
More informationMultithreaded Programming
Multithreaded Programming Multithreaded programming basics Concurrency is the ability to run multiple parts of the program in parallel. In Concurrent programming, there are two units of execution: Processes
More informationThreads Questions Important Questions
Threads Questions Important Questions https://dzone.com/articles/threads-top-80-interview https://www.journaldev.com/1162/java-multithreading-concurrency-interviewquestions-answers https://www.javatpoint.com/java-multithreading-interview-questions
More informationModule - 4 Multi-Threaded Programming
Terminologies Module - 4 Multi-Threaded Programming Process: A program under execution is called as process. Thread: A smallest component of a process that can be executed independently. OR A thread is
More informationTHREADS AND CONCURRENCY
THREADS AND CONCURRENCY Lecture 22 CS2110 Spring 2013 Graphs summary 2 Dijkstra: given a vertex v, finds shortest path from v to x for each vertex x in the graph Key idea: maintain a 5-part invariant on
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Spring 2018 Reading: Chapter 2, Relevant Links - Threads Some Material in these slides from J.F Kurose and K.W. Ross All material
More informationContents. 6-1 Copyright (c) N. Afshartous
Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 6-1 Copyright (c) 1999-2004
More informationThreads and Locks. CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015
Threads and Locks CSCI 5828: Foundations of Software Engineering Lecture 09 09/22/2015 1 Goals Cover the material presented in Chapter 2, Day 1 of our concurrency textbook Creating threads Locks Memory
More informationUnit - IV Multi-Threading
Unit - IV Multi-Threading 1 Uni Processing In the early days of computer only one program will occupy the memory. The second program must be in waiting. The second program will be entered whenever first
More informationCSCD 330 Network Programming
CSCD 330 Network Programming Lecture 8 Client-Server Programming Threads Spring 2017 Reading: Chapter 2, Relevant Links - Threads Some Material in these slides from J.F Kurose and K.W. Ross All material
More informationProgramming Language Concepts: Lecture 11
Programming Language Concepts: Lecture 11 Madhavan Mukund Chennai Mathematical Institute madhavan@cmi.ac.in PLC 2011, Lecture 11, 01 March 2011 Concurrent Programming Monitors [Per Brinch Hansen, CAR Hoare]
More informationMultiple Inheritance. Computer object can be viewed as
Multiple Inheritance We have seen that a class may be derived from a given parent class. It is sometimes useful to allow a class to be derived from more than one parent, inheriting members of all parents.
More informationNetworking, Java threads and synchronization. PRIS lecture 4 Fredrik Kilander
Networking, Java threads and synchronization PRIS lecture 4 Fredrik Kilander OSI Application Presentation Session Transport Network Data link Physical TCP/IP Application Transport Internet Host-to-network
More informationDefinition: A thread is a single sequential flow of control within a program.
What Is a Thread? All programmers are familiar with writing sequential programs. You've probably written a program that displays "Hello World!" or sorts a list of names or computes a list of prime numbers.
More informationG51PGP Programming Paradigms. Lecture 009 Concurrency, exceptions
G51PGP Programming Paradigms Lecture 009 Concurrency, exceptions 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals = new Animal[6]; animals[0]
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationSynchronization
Synchronization 10-28-2013 Synchronization Coming next: Multithreading in JavaFX (javafx.concurrent) Read: Java Tutorial on concurrency JavaFX Tutorial on concurrency Effective Java, Chapter 9 Project#1:
More informationSynchronization in Concurrent Programming. Amit Gupta
Synchronization in Concurrent Programming Amit Gupta Announcements Project 1 grades are out on blackboard. Detailed Grade sheets to be distributed after class. Project 2 grades should be out by next Thursday.
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Threads Synchronization Refers to mechanisms allowing a programmer to control the execution order of some operations across different threads in a concurrent
More informationAn Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006. Thread Creation
An Introduction to Programming with Java Threads Andrew Whitaker University of Washington 9/13/2006 This document provides a brief introduction to programming with threads in Java. I presume familiarity
More informationECE 462 Object-Oriented Programming using C++ and Java. Scheduling and Critical Section
ECE 462 Object-Oriented Programming g using C++ and Java Scheduling and Critical Section Yung-Hsiang Lu yunglu@purdue.edu d YHL Scheduling and Critical Section 1 Thread States born terminated ready running
More informationAmity School of Engineering
Amity School of Engineering B.Tech., CSE(5 th Semester) Java Programming Topic: Multithreading ANIL SAROLIYA 1 Multitasking and Multithreading Multitasking refers to a computer's ability to perform multiple
More informationSynchronization SPL/2010 SPL/20 1
Synchronization 1 Overview synchronization mechanisms in modern RTEs concurrency issues places where synchronization is needed structural ways (design patterns) for exclusive access 2 Overview synchronization
More informationMultiprocessing Threads/Lightweight objects Thread methods Concurrency Issues
Concurrency Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues What is program execution? In order to run, a program must be loaded into memory and given an initial state. Code
More informationCS455: Introduction to Distributed Systems [Spring 2019] Dept. Of Computer Science, Colorado State University
CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] The House of Heap and Stacks Stacks clean up after themselves But over deep recursions they fret The cheerful heap has nary a care Harboring memory
More informationMultiprocessing Threads/Lightweight objects Thread methods Concurrency Issues
Concurrency Multiprocessing Threads/Lightweight objects Thread methods Concurrency Issues What is program execution? In order to run, a program must be loaded into memory and given an initial state. Code
More informationSynchronization synchronization.
Unit 4 Synchronization of threads using Synchronized keyword and lock method- Thread pool and Executors framework, Futures and callable, Fork-Join in Java. Deadlock conditions 1 Synchronization When two
More informationSUMMARY INTRODUCTION CONCURRENT PROGRAMMING THREAD S BASICS. Introduction Thread basics. Thread states. Sequence diagrams
SUMMARY CONCURRENT PROGRAMMING THREAD S BASICS PROGRAMMAZIONE CONCORRENTE E DISTR. Introduction Thread basics Thread properties Thread states Thread interruption Sequence diagrams Università degli Studi
More informationCOMP 322: Fundamentals of Parallel Programming
COMP 322: Fundamentals of Parallel Programming https://wiki.rice.edu/confluence/display/parprog/comp322 Lecture 28: Java Threads (contd), synchronized statement Vivek Sarkar Department of Computer Science
More informationBackground. vanilladb.org
Background vanilladb.org Why do you need a database system? 2 To store data, why not just use a file system? 3 Advantages of a Database System It answers queries fast Q1: among a set of blog pages, find
More informationAdvanced Java Programming Course. MultiThreading. By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City
Advanced Java Programming Course MultiThreading By Võ Văn Hải Faculty of Information Technologies Industrial University of Ho Chi Minh City Session objectives Introduction Creating thread Thread class
More informationCST242 Concurrency Page 1
CST242 Concurrency Page 1 1 2 3 4 5 6 7 9 Concurrency CST242 Concurrent Processing (Page 1) Only computers with multiple processors can truly execute multiple instructions concurrently On single-processor
More informationCS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Frequently asked questions from the previous class survey
CS 455: INTRODUCTION TO DISTRIBUTED SYSTEMS [THREADS] Shrideep Pallickara Computer Science Colorado State University L6.1 Frequently asked questions from the previous class survey L6.2 SLIDES CREATED BY:
More informationCS360 Lecture 12 Multithreading
CS360 Lecture 12 Multithreading Thursday, March 11, 2004 Reading Multithreading: Chapter 16 Thread States At any time, a thread can be in one of several thread states: - Born: this is the time when the
More informationSoftware Practice 1 - Multithreading
Software Practice 1 - Multithreading What is the thread Life cycle of thread How to create thread Thread method Lab practice Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim T.A. Sujin Oh Junseong Lee
More informationCMSC 330: Organization of Programming Languages
CMSC 330: Organization of Programming Languages Multithreading Multiprocessors Description Multiple processing units (multiprocessor) From single microprocessor to large compute clusters Can perform multiple
More informationConcurrent Programming
Concurrency Concurrent Programming A sequential program has a single thread of control. Its execution is called a process. A concurrent program has multiple threads of control. They may be executed as
More informationCSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015
CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2015 Name: This exam consists of 5 problems on the following 7 pages. You may use your double- sided hand- written 8 ½ x 11 note sheet
More informationRobotics and Autonomous Systems
1 / 38 Robotics and Autonomous Systems Lecture 10: Threads and Multitasking Robots Simon Parsons Department of Computer Science University of Liverpool 2 / 38 Today Some more programming techniques that
More informationClass, Variable, Constructor, Object, Method Questions
Class, Variable, Constructor, Object, Method Questions http://www.wideskills.com/java-interview-questions/java-classes-andobjects-interview-questions https://www.careerride.com/java-objects-classes-methods.aspx
More informationTHREADS AND MULTITASKING ROBOTS
ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 comp329-2013-parsons-lect10 2/37 Today Some more programming techniques that will be helpful
More informationROBOTICS AND AUTONOMOUS SYSTEMS
ROBOTICS AND AUTONOMOUS SYSTEMS Simon Parsons Department of Computer Science University of Liverpool LECTURE 10 THREADS AND MULTITASKING ROBOTS comp329-2013-parsons-lect10 2/37 Today Some more programming
More informationQuiz on Tuesday April 13. CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4. Java facts and questions. Things to try in Java
CS 361 Concurrent programming Drexel University Fall 2004 Lecture 4 Bruce Char and Vera Zaychik. All rights reserved by the author. Permission is given to students enrolled in CS361 Fall 2004 to reproduce
More informationReading from URL. Intent - open URL get an input stream on the connection, and read from the input stream.
Simple Networking Loading applets from the network. Applets are referenced in a HTML file. Java programs can use URLs to connect to and retrieve information over the network. Uniform Resource Locator (URL)
More informationNeed for synchronization: If threads comprise parts of our software systems, then they must communicate.
Thread communication and synchronization There are two main aspects to Outline for Lecture 19 multithreaded programming in Java: I. Thread synchronization. thread lifecycle, and thread synchronization.
More informationBy: Abhishek Khare (SVIM - INDORE M.P)
By: Abhishek Khare (SVIM - INDORE M.P) MCA 405 Elective I (A) Java Programming & Technology UNIT-2 Interface,Multithreading,Exception Handling Interfaces : defining an interface, implementing & applying
More information