SlideShare une entreprise Scribd logo
1  sur  36
Concurrent Programming CS 3331 Fall 2007
Outline ,[object Object],[object Object],[object Object],[object Object],[object Object]
Concurrent Programming ,[object Object],[object Object]
Multithreaded Programming ,[object Object],[object Object],[object Object],[object Object],flow of control sequential  concurrent
Why? ,[object Object],[object Object],[object Object],[object Object],[object Object]
But, ,[object Object],[object Object],[object Object]
Creating Threads in Java ,[object Object],[object Object],[object Object]
Creating Threads (Cont.) ,[object Object],public class MyThread extends Thread { public void run() { // the thread body } // other methods and fields. } // Start a new thread by calling the start method MyThread thread = new MyThread(); thread.start(); // … flow of control start() run() // … The method run is the concurrent unit in Java.
Creating Threads (Cont.) ,[object Object],public interface Runnable { void run(); } public class MyThread implements Runnable { public void run() { // the thread body } // other methods and fields. } // Start a new thread by creating an instance and calling the start method, e.g., new Thread(new MyThread()).start();
Example --- Simple Counter public class Counter extends Thead { private int count, inc, delay; public Counter(int init, int inc, int delay) { this.count = init; this.inc = inc; this.delay = delay; } public void run() { try { for (;;) { System.out.print(count + “ “); count += inc; sleep(delay); } } catch (InterruptedException e) {} } public static void main(String[] args) { new Counter(0, 1, 33).start(); new Counter(0, -1, 100).start(); } }
Example (Cont.) Output: 0 0 1 2 -1 3 4 5 -2 6 7 8 -3 9 10 -4 11 12 13  -5 14 15 16 -6 17 18 -7 19 20 21 -8 22 23 24 -9 25 26 -10 27 28 -11 29 30 31 -12 32 33 34 -13 35 36 37 -14 38 39 -15 40 41 42 -16 43 44 45 … Q: What will happen if we change the statement “new Counter().start()” to “new Counter().run()” in the main method?
Exercise Write a thread class named Talker that prints a hello message, say “Hello, I am Tom!”, continuously, and create two instances as separate threads.  public class Talker _______________________ { private String name; public Talker(String name) {  this.name = name;  } }
Controlling Threads ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],start Non-runnable New Dead Runnable yield sleep join end of run Alive
Methods of Thread Class Method  Description start() Enter the  Runnable  state from the  new  state  *sleep() Enter the  Non-runnable  state join() Enter the  Non-runnable  state and wait for another thread to terminate *yield() Release CPU and remain in the  Runnable interrupt() Cause InterruptedException isAlive() True if in the  alive  state isInterrupted() True if interrupted * static method
Example Coordinating concurrent jobs public class Job extends Thread { public void run() {  // do some meaningful work, e.g.,  writing multithreaded applets. } public static void main(String[] args) { Job[] jobs = new Job[10]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(); jobs[i].start(); } for (int i = 0; i < jobs.length; i++) { jobs[i].join(); } } } jobs[0] … jobs[9] main
Exercise Explain the execution flow of the following program. public class Job extends Thread { public void run() {  // do some meaningful work, e.g.,  writing multithreaded applets. } public static void main(String[] args) { Job[] jobs = new Job[10]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(); jobs[i].start(); jobs[i].join(); } } }
Thread Safety ,[object Object],public class Account { private long balance; public boolean withdraw(long amount) { if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } // other methods and fields } ,[object Object]
Example (Cont.) ,[object Object],Assume that the initial balance is $1,000,000, and two withdraw requests of $1,000,000 are made almost simultaneously.  time  balance  withdraw 1  withdraw 2 t1  1,000,000  amount<=balance  t2  1,000,000  amount<=balance  t3  1,000,000  newbalance=...;  t4  1,000,000  newbalance=...;  t5  0  balance=...;  t6  0  balance=...;  t7  0  return true;  t8  0  return true; if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; }
Atomicity of Operations ,[object Object],[object Object],[object Object],[object Object],[object Object]
Making methods atomic ,[object Object],[object Object],// synchronized method synchronized  void aMethod() { // do something } // synchronized statement synchronized  (expr) { // expr should be of a reference type! // do somthing }
Example public class Account { private long balance; public  synchronized  boolean withdraw(long amount) { if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } // other methods and fields }
Exercise Make withdraw method synchronized by using the synchronized statement. public class Account { private long balance; public boolean withdraw(long amount) { // WRITE YOUR CODE HERE… if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } }
Synchronization ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Example --- Bounded Queue A first-in, first-out queue with a fixed capacity public class BoundedQueue { protected Object rep[]; // circular array protected int front = 0; // front of the queue protected int back = -1; // back of the queue protected int size; // capacity of the queue protected int count = 0; // num of objects in the queue //@ requires size > 0; public BoundedQueue(int size) { this.size = size; rep = new Object[size]; back = size – 1; } public boolean isEmpty() { return (count == 0); }
Bounded Queue (Cont.) public boolean isFull() { return (count == size); }  public int getCount() { return count; } public void put(/*@ non_null @*/ Object e) { if (!isFull()) { back = (back + 1) % size; rep[back] = e; count++; } } public Object get() { Object result = null; if (!isEmpty()) { result = rep[front]; front = (front + 1) % size; count--; } return result; }  }
Making Queue Thread-Safe public class SyncBoundedQueue extends BoundedQueue { public SyncBoundedQueue(int size) { super(size); } public  synchronized  boolean isEmpty() { return super.isEmpty(); } public  synchronized  boolean isFull() { return super.isFull(); } public  synchronized  int getCount() { return super.getCount(); } public  synchronized  void put(Object e) { super.put(e); } public  synchronized  Object get() { return super.get(); } }
Use of Bounded Queue Typical use in producers and consumers Thread Thief Broker SyncBoundedQueue
Producer public class Thief extends Thread { private BoundedQueue queue; private int n; // number of items to steal public Producer(BoundedQueue queue, int n) { this.queue = queue; this.n = n; } public void run() { for (int i = 0; i < n; i++) { queue.put(new Integer(i)); System.out.println(“produced: “ + i); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) {} } } }
Consumer public class Broker extends Thread { private BoundedQueue queue; private int n; // number of stolen items to sell public Consumer(BoundedQueue queue, int n) { this.queue = queue; this.n = n; } public void run() { for (int i = 0; i < n; i++) { Object obj = queue.get(); System.out.println(“consumed: “ + obj); try { sleep((int) (Math.random() * 400)); } catch (InterruptedException e) {} } } }
Sample Main Program The main method of class SyncBoundedQueue public static void main(String[] args) { SyncBoundedQueue queue = new SyncBoundedQueue(5); new Thief(queue, 15).start(); // produce 15 items new Broker(queue, 10).start(); // consume 10 items } Output Some of the items might be lost, as the producer produces items faster than the consumer consumes them.
Cooperation among Threads ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Thread Methods of Class Object Method    Description wait()   Temporarily blocked and placed in the wait queue   of the receiving object.  notify()   Awaken one of the threads in the wait queue    associated with the receiving object and remove it   from the queue. notifyAll() Same as notify() except that all threads in the wait    queue are awakened.
Bounded Queue with Guarded Suspension public class BoundedQueueWithGuard extends BoundedQueue { public Producer(int size) { super(size); } public synchronized boolean isEmpty() {  return super.isEmpty();  } public synchronized boolean isFull() {  return super.isFull();  } public synchronized int getCount() {  return super.getCount();  } <<put, get, and main method>> }
Put Method public synchronized void put(Object obj) { try { while (isFull()) { wait(); } } catch (InterruptedException e) {} super.put(e); notify(); }
Exercise --- Get Method Write the get method with guarded suspension. public synchronized Object get() { // WRITE YOUR CODE HERE. }
Smart Thief and Broker public static void main(String args[]) { BoundedQueueWithGuard queue = new BoundedQueueWithGuard(5); new Thief(queue, 15).start(); // produce 15 items. new Broker(queue, 15).start(); // consume 15 times } Output: No lost items!

Contenu connexe

Tendances

Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Sergey Platonov
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance PuzzlersDoug Hawkins
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 

Tendances (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Java Performance Puzzlers
Java Performance PuzzlersJava Performance Puzzlers
Java Performance Puzzlers
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Class method
Class methodClass method
Class method
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java programs
Java programsJava programs
Java programs
 

En vedette

5.Dns Rpc Nfs
5.Dns Rpc Nfs5.Dns Rpc Nfs
5.Dns Rpc Nfsphanleson
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbcphanleson
 
7.Canon & Dt
7.Canon & Dt7.Canon & Dt
7.Canon & Dtphanleson
 
2.Public Vulnerability Databases
2.Public Vulnerability Databases2.Public Vulnerability Databases
2.Public Vulnerability Databasesphanleson
 
7.Trust Management
7.Trust Management7.Trust Management
7.Trust Managementphanleson
 
Ch09 Information Security Best Practices
Ch09 Information Security Best PracticesCh09 Information Security Best Practices
Ch09 Information Security Best Practicesphanleson
 

En vedette (9)

Rmi
RmiRmi
Rmi
 
5.Dns Rpc Nfs
5.Dns Rpc Nfs5.Dns Rpc Nfs
5.Dns Rpc Nfs
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
7.Canon & Dt
7.Canon & Dt7.Canon & Dt
7.Canon & Dt
 
2.Public Vulnerability Databases
2.Public Vulnerability Databases2.Public Vulnerability Databases
2.Public Vulnerability Databases
 
Ch06 Policy
Ch06 PolicyCh06 Policy
Ch06 Policy
 
7.Trust Management
7.Trust Management7.Trust Management
7.Trust Management
 
Ch09 Information Security Best Practices
Ch09 Information Security Best PracticesCh09 Information Security Best Practices
Ch09 Information Security Best Practices
 

Similaire à Thread

Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel GeheugenDevnology
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical FileFahad Shaikh
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Java concurrency
Java concurrencyJava concurrency
Java concurrencyducquoc_vn
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4Abed Bukhari
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronizationpriyabogra1
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 

Similaire à Thread (20)

04 threads
04 threads04 threads
04 threads
 
Software Transactioneel Geheugen
Software Transactioneel GeheugenSoftware Transactioneel Geheugen
Software Transactioneel Geheugen
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Java practical
Java practicalJava practical
Java practical
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Whats new in_csharp4
Whats new in_csharp4Whats new in_csharp4
Whats new in_csharp4
 
Thread syncronization
Thread syncronizationThread syncronization
Thread syncronization
 
Java Generics
Java GenericsJava Generics
Java Generics
 

Plus de phanleson

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Sparkphanleson
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewallsphanleson
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hackingphanleson
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocolsphanleson
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacksphanleson
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applicationsphanleson
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designphanleson
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operationsphanleson
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBasephanleson
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibphanleson
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streamingphanleson
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLphanleson
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Clusterphanleson
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programmingphanleson
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Dataphanleson
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairsphanleson
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Sparkphanleson
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagiaphanleson
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLphanleson
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Webphanleson
 

Plus de phanleson (20)

Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
 
Firewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth FirewallsFirewall - Network Defense in Depth Firewalls
Firewall - Network Defense in Depth Firewalls
 
Mobile Security - Wireless hacking
Mobile Security - Wireless hackingMobile Security - Wireless hacking
Mobile Security - Wireless hacking
 
Authentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless ProtocolsAuthentication in wireless - Security in Wireless Protocols
Authentication in wireless - Security in Wireless Protocols
 
E-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server AttacksE-Commerce Security - Application attacks - Server Attacks
E-Commerce Security - Application attacks - Server Attacks
 
Hacking web applications
Hacking web applicationsHacking web applications
Hacking web applications
 
HBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table designHBase In Action - Chapter 04: HBase table design
HBase In Action - Chapter 04: HBase table design
 
HBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - OperationsHBase In Action - Chapter 10 - Operations
HBase In Action - Chapter 10 - Operations
 
Hbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBaseHbase in action - Chapter 09: Deploying HBase
Hbase in action - Chapter 09: Deploying HBase
 
Learning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlibLearning spark ch11 - Machine Learning with MLlib
Learning spark ch11 - Machine Learning with MLlib
 
Learning spark ch10 - Spark Streaming
Learning spark ch10 - Spark StreamingLearning spark ch10 - Spark Streaming
Learning spark ch10 - Spark Streaming
 
Learning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQLLearning spark ch09 - Spark SQL
Learning spark ch09 - Spark SQL
 
Learning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a ClusterLearning spark ch07 - Running on a Cluster
Learning spark ch07 - Running on a Cluster
 
Learning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark ProgrammingLearning spark ch06 - Advanced Spark Programming
Learning spark ch06 - Advanced Spark Programming
 
Learning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your DataLearning spark ch05 - Loading and Saving Your Data
Learning spark ch05 - Loading and Saving Your Data
 
Learning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value PairsLearning spark ch04 - Working with Key/Value Pairs
Learning spark ch04 - Working with Key/Value Pairs
 
Learning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with SparkLearning spark ch01 - Introduction to Data Analysis with Spark
Learning spark ch01 - Introduction to Data Analysis with Spark
 
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about LibertagiaHướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
Hướng Dẫn Đăng Ký LibertaGia - A guide and introduciton about Libertagia
 
Lecture 1 - Getting to know XML
Lecture 1 - Getting to know XMLLecture 1 - Getting to know XML
Lecture 1 - Getting to know XML
 
Lecture 4 - Adding XTHML for the Web
Lecture  4 - Adding XTHML for the WebLecture  4 - Adding XTHML for the Web
Lecture 4 - Adding XTHML for the Web
 

Thread

  • 1. Concurrent Programming CS 3331 Fall 2007
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10. Example --- Simple Counter public class Counter extends Thead { private int count, inc, delay; public Counter(int init, int inc, int delay) { this.count = init; this.inc = inc; this.delay = delay; } public void run() { try { for (;;) { System.out.print(count + “ “); count += inc; sleep(delay); } } catch (InterruptedException e) {} } public static void main(String[] args) { new Counter(0, 1, 33).start(); new Counter(0, -1, 100).start(); } }
  • 11. Example (Cont.) Output: 0 0 1 2 -1 3 4 5 -2 6 7 8 -3 9 10 -4 11 12 13 -5 14 15 16 -6 17 18 -7 19 20 21 -8 22 23 24 -9 25 26 -10 27 28 -11 29 30 31 -12 32 33 34 -13 35 36 37 -14 38 39 -15 40 41 42 -16 43 44 45 … Q: What will happen if we change the statement “new Counter().start()” to “new Counter().run()” in the main method?
  • 12. Exercise Write a thread class named Talker that prints a hello message, say “Hello, I am Tom!”, continuously, and create two instances as separate threads. public class Talker _______________________ { private String name; public Talker(String name) { this.name = name; } }
  • 13.
  • 14. Methods of Thread Class Method Description start() Enter the Runnable state from the new state *sleep() Enter the Non-runnable state join() Enter the Non-runnable state and wait for another thread to terminate *yield() Release CPU and remain in the Runnable interrupt() Cause InterruptedException isAlive() True if in the alive state isInterrupted() True if interrupted * static method
  • 15. Example Coordinating concurrent jobs public class Job extends Thread { public void run() { // do some meaningful work, e.g., writing multithreaded applets. } public static void main(String[] args) { Job[] jobs = new Job[10]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(); jobs[i].start(); } for (int i = 0; i < jobs.length; i++) { jobs[i].join(); } } } jobs[0] … jobs[9] main
  • 16. Exercise Explain the execution flow of the following program. public class Job extends Thread { public void run() { // do some meaningful work, e.g., writing multithreaded applets. } public static void main(String[] args) { Job[] jobs = new Job[10]; for (int i = 0; i < jobs.length; i++) { jobs[i] = new Job(); jobs[i].start(); jobs[i].join(); } } }
  • 17.
  • 18.
  • 19.
  • 20.
  • 21. Example public class Account { private long balance; public synchronized boolean withdraw(long amount) { if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } // other methods and fields }
  • 22. Exercise Make withdraw method synchronized by using the synchronized statement. public class Account { private long balance; public boolean withdraw(long amount) { // WRITE YOUR CODE HERE… if (amount <= balance) { long newBalance = balance – amount; balance = newBalance; return true; } else { return false; } } }
  • 23.
  • 24. Example --- Bounded Queue A first-in, first-out queue with a fixed capacity public class BoundedQueue { protected Object rep[]; // circular array protected int front = 0; // front of the queue protected int back = -1; // back of the queue protected int size; // capacity of the queue protected int count = 0; // num of objects in the queue //@ requires size > 0; public BoundedQueue(int size) { this.size = size; rep = new Object[size]; back = size – 1; } public boolean isEmpty() { return (count == 0); }
  • 25. Bounded Queue (Cont.) public boolean isFull() { return (count == size); } public int getCount() { return count; } public void put(/*@ non_null @*/ Object e) { if (!isFull()) { back = (back + 1) % size; rep[back] = e; count++; } } public Object get() { Object result = null; if (!isEmpty()) { result = rep[front]; front = (front + 1) % size; count--; } return result; } }
  • 26. Making Queue Thread-Safe public class SyncBoundedQueue extends BoundedQueue { public SyncBoundedQueue(int size) { super(size); } public synchronized boolean isEmpty() { return super.isEmpty(); } public synchronized boolean isFull() { return super.isFull(); } public synchronized int getCount() { return super.getCount(); } public synchronized void put(Object e) { super.put(e); } public synchronized Object get() { return super.get(); } }
  • 27. Use of Bounded Queue Typical use in producers and consumers Thread Thief Broker SyncBoundedQueue
  • 28. Producer public class Thief extends Thread { private BoundedQueue queue; private int n; // number of items to steal public Producer(BoundedQueue queue, int n) { this.queue = queue; this.n = n; } public void run() { for (int i = 0; i < n; i++) { queue.put(new Integer(i)); System.out.println(“produced: “ + i); try { sleep((int) (Math.random() * 100)); } catch (InterruptedException e) {} } } }
  • 29. Consumer public class Broker extends Thread { private BoundedQueue queue; private int n; // number of stolen items to sell public Consumer(BoundedQueue queue, int n) { this.queue = queue; this.n = n; } public void run() { for (int i = 0; i < n; i++) { Object obj = queue.get(); System.out.println(“consumed: “ + obj); try { sleep((int) (Math.random() * 400)); } catch (InterruptedException e) {} } } }
  • 30. Sample Main Program The main method of class SyncBoundedQueue public static void main(String[] args) { SyncBoundedQueue queue = new SyncBoundedQueue(5); new Thief(queue, 15).start(); // produce 15 items new Broker(queue, 10).start(); // consume 10 items } Output Some of the items might be lost, as the producer produces items faster than the consumer consumes them.
  • 31.
  • 32. Thread Methods of Class Object Method Description wait() Temporarily blocked and placed in the wait queue of the receiving object. notify() Awaken one of the threads in the wait queue associated with the receiving object and remove it from the queue. notifyAll() Same as notify() except that all threads in the wait queue are awakened.
  • 33. Bounded Queue with Guarded Suspension public class BoundedQueueWithGuard extends BoundedQueue { public Producer(int size) { super(size); } public synchronized boolean isEmpty() { return super.isEmpty(); } public synchronized boolean isFull() { return super.isFull(); } public synchronized int getCount() { return super.getCount(); } <<put, get, and main method>> }
  • 34. Put Method public synchronized void put(Object obj) { try { while (isFull()) { wait(); } } catch (InterruptedException e) {} super.put(e); notify(); }
  • 35. Exercise --- Get Method Write the get method with guarded suspension. public synchronized Object get() { // WRITE YOUR CODE HERE. }
  • 36. Smart Thief and Broker public static void main(String args[]) { BoundedQueueWithGuard queue = new BoundedQueueWithGuard(5); new Thief(queue, 15).start(); // produce 15 items. new Broker(queue, 15).start(); // consume 15 times } Output: No lost items!

Notes de l'éditeur

  1. Squential : tuần tự Concurrently : đồng thời, kiêm
  2. Reactive : tác động trở lại, ảnh hưởng trở lại Suitable : phù hợp, thích hợp
  3. synchronized public Object get() { try { while (isEmpty()) { wait(); } } catch (InterruptedException e) {} Object result = super.get(); notify(); return result; }
  4. public synchronized Object get() { try { while (isEmpty()) { wait(); } } catch (InterruptedException e) {} Object result = super.get(); notify(); return result; }