10. Multithreading 1 public class SumTest { public static void main(String a1[]) public static void main(String a1[]) { int a, b, sum; int a, b, sum; a.

Slides:



Advertisements
Similar presentations
Unit 141 Threads What is a Thread? Multithreading Creating Threads – Subclassing java.lang.Thread Example 1 Creating Threads – Implementing java.lang.Runnable.
Advertisements

Algorithm Programming Concurrent Programming in Java Bar-Ilan University תשס"ח Moshe Fresko.
Slides 8c-1 Programming with Shared Memory Java Threads and Synchronization Review The following notes are based upon the Java tutorial at
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
Java Programming Transparency No. 1 Lecture 7. Java Threads Cheng-Chia Chen.
Concurrency Java Threads. Fundamentals Concurrency defines parallel activity Synchronization is necessary in order for parallel activities to share results.
Definitions Process – An executing program
Jan Java Threads Yangjun Chen Dept. Business Computing University of Winnipeg.
Multithreading in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Threads Just Java: C10–pages 251- C11–pages 275-
Java Threads CS Introduction to Operating Systems.
Java Programming Transparency No. 1 Lecture 7. Java Threads Cheng-Chia Chen.
Lecture 4 : JAVA Thread Programming
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
Java Programming: Advanced Topics
1 Java Threads and Synchronization Review Modified from slides taken from
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Lecture 5 : JAVA Thread Programming Courtesy : MIT Prof. Amarasinghe and Dr. Rabbah’s course note.
Quick overview of threads in Java Babak Esfandiari (extracted from Qusay Mahmoud’s slides)
Online Appointment Book Implement a Client/Server application for an online appointment book. Client should be a Graphical User Interface application.
Today’s Agenda  Quick Review  Finish Java Threads  The CS Problem Advanced Topics in Software Engineering 1.
Concurrent Programming in Java Dr. Zoltan Papp. Motivation: event driven, responsive systems Sequential approach: while ( true ) { do event = getEventId()
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
Dr. R R DOCSIT, Dr BAMU. Basic Java : Multi Threading 2 Objectives of This Session State what is Multithreading. Describe the life cycle of Thread.
Threads in Java. Processes and Threads Processes –A process has a self-contained execution environment. –Has complete set of runtime resources including.
Threads.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
1 5.0 Garbage collector & Threads : Overview Introduction: In this module we discuss the merits and demerits of automated garbage collection over manual.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 18 Advanced Java Concepts Threads and Multithreading.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Multithreading in JAVA
Object-oriented Programming in Java. © Aptech Ltd. Introduction to Threads/Session 7 2  Introduction to Threads  Creating Threads  Thread States 
Java Thread and Memory Model
Packages Packages are containers for classes that are used to keep the class name space compartmentalized.. You can define classes inside a package that.
Java 3: Odds & Ends Advanced Programming Techniques.
Concurrent Computing CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Multithreaded programming  Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run.
Threads in Java Threads Introduction: After completing this chapter, you will be able to code your own thread, control them efficiently without.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
1 Java Programming Java Programming II Concurrent Programming: Threads ( I)
Multithreading. Multitasking The multitasking is the ability of single processor to perform more than one operation at the same time Once systems allowed.
Threads b A thread is a flow of control in a program. b The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
Chapter 13: Multithreading The Thread class The Thread class The Runnable Interface The Runnable Interface Thread States Thread States Thread Priority.
1 Multithreading in Java THETOPPERSWAY.COM. 2 Outline  Multithreading & Thread Introduction  Creating threads  Thread Life Cycle  Threads priorities.
Multithreading / Concurrency
Multithreading Lec 23.
Chapter 13: Multithreading
Java Multithreading.
Multithreading.
Multithreading in Java
Threads Chate Patanothai.
Definitions Concurrent program – Program that executes multiple instructions at the same time. Process – An executing program (the running JVM for Java.
Exception Handling Visit for more Learning Resources.
Multithreading.
Multithreading 2 Lec 24.
Java Based Techhnology
Principles of Software Development
Multithreading.
13: Concurrency Definition:  A thread is a single sequential flow of control within a program. Some texts use the name lightweight process instead of thread.
Multithreaded Programming
Programming with Shared Memory Java Threads and Synchronization
Programming with Shared Memory Java Threads and Synchronization
برنامه‌نویسی چندنخی Multi-Thread Programming
Java Thread.
Chapter 15 Multithreading
Computer Science 2 06A-Java Multithreading
Multithreading in java.
Representation and Management of Data on the Internet
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

10. Multithreading 1 public class SumTest { public static void main(String a1[]) public static void main(String a1[]) { int a, b, sum; int a, b, sum; a = Integer.parseInt(a1[0]); a = Integer.parseInt(a1[0]); b = Integer.parseInt(a1[1]); b = Integer.parseInt(a1[1]); sum = a + b ; // 두 수를 더하는 부분입니다 sum = a + b ; // 두 수를 더하는 부분입니다 System.out.println(" 두수의 합은 " + sum + " 입니다 "); System.out.println(" 두수의 합은 " + sum + " 입니다 "); }}

2 Multiple threads on multiple CPUs Multiple threads sharing a single CPU Threads Concept

10 장. 다중 스레드 3 Thread Class  java.lang Package Thread() Thread(String s) Thread(Runnable r) Thread(Runnable r, String s)

10 장. 다중 스레드 4 Method Description static void sleep(long msec) throws InterruptedException Causes the currently executing thread to sleep (temporarily cease execution) for the specifie d number of milliseconds, subject to the precision and accuracy of system timers and schedul ers. static void sleep(long msec, int nsec) throws InterruptedException Causes the currently executing thread to sleep (temporarily cease execution) for the specifie d number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. String getName()Returns this thread's name. void setName(String s)Changes the name of this thread to be equal to the argument name. void start() Causes this thread to begin execution; the Java Virtual Machine calls the run method of this t hread. final int getPriority()Returns this thread's priority. final void setPriority(int p)Changes the priority of this thread. void join() throws InterruptedExceptionWaits for this thread to die. void run() If this thread was constructed using a separate Runnable run object, then that Runnable obje ct's run method is called; otherwise, this method does nothing and returns. void suspend()This method has been deprecated, as it is inherently deadlock-prone void resume() This method exists solely for use with suspend(), which has been deprecated because it is de adlock-pronesuspend()

10 장. 다중 스레드 5 StateMachine diagram

10 장. 다중 스레드 6 Thread states  New  Runnable(ready)  Running(executing)  Waiting  Dead(finished)

10 장. 다중 스레드 7 Thread Class class ThreadA extends Thread { public void run() {.... } } ThreadA ta = new ThreadA(); ta.start();

10 장. 다중 스레드 8 Runnable Interface class RunnableB extends Applet implements Runnable { public void run() { } } public interface Runnable { public void run(); }

10 장. 다중 스레드 9 Example RunnableB rb = new RunnableB(); Thread tb = new Thread(rb); tb.start(); RunnableB rb = new RunnableB(); new Thread(rb).start();

10 장. 다중 스레드 10 Exercises ThreadFromThread.java class ThreadTest extends Thread { public void run() { for (int i=1 ; i<=10 ; i++) { System.out.println(“Java :" + i); } public class ThreadFromThread { public static void main(String args[]) { ThreadTest t = new ThreadTest(); t.start(); }

10 장. 다중 스레드 11 Java : 1 Java : 2 Java : 3 Java : 4 Java : 5 Java : 6 Java : 7 Java : 8 Java : 9 Java : 10

10 장. 다중 스레드 12 Exercises ThreadFromRunnable.java class RunnableTest implements Runnable { public void run() { for (int i=1 ; i<=10 ; i++) { System.out.println(“Java :" + i); } public class ThreadFromRunnable { public static void main(String args[]) { RunnableTest r = new RunnableTest(); Thread t = new Thread(r); t.start(); }

10 장. 다중 스레드 13 Java : 1 Java : 2 Java : 3 Java : 4 Java : 5 Java : 6 Java : 7 Java : 8 Java : 9 Java : 10

10 장. 다중 스레드 14 Exercises DoubleThread.java class ThreadTest1 extends Thread { public ThreadTest1(String str) { setName(str); } public void run() { for (int i=1 ; i<=10 ; i++) { System.out.println(i + getName()); } System.out.println(“End" + getName()); } public class DoubleThread { public static void main(String args[]) { ThreadTest1 t1 = new ThreadTest1 (" : Thread1"); ThreadTest1 t2 = new ThreadTest1 (" : Thread2"); t1.start(); t2.start(); }

10 장. 다중 스레드 15 1: Thread1 1: Thread2 2: Thread1 2: Thread2 3: Thread1 3: Thread2 4: Thread1 4: Thread2 5: Thread1 5: Thread2 6: Thread1 6: Thread2 7: Thread1 7: Thread2 8: Thread1 8: Thread2 9: Thread1 9: Thread2 10: Thread1 10: Thread2 End: Thread1 End: Thread2

10 장. 다중 스레드 16 1: Thread2 1: Thread1 2: Thread2 2: Thread1 3: Thread2 3: Thread1 4: Thread2 4: Thread1 5: Thread2 5: Thread1 6: Thread2 6: Thread1 7: Thread2 7: Thread1 8: Thread2 8: Thread1 9: Thread2 9: Thread1 10: Thread2 10: Thread1 End: Thread2 End: Thread1

10 장. 다중 스레드 17 setPriority()  Changes the priority of this thread. static final int MAX_PRIORITY ← priority : 10 static final int MIN_PRIORITY ← priority : 1 static final int NORM_PRIORITY ← priority : 5

10 장. 다중 스레드 18 Excercises ThreadPriority.java class PriorityTest extends Thread{ public PriorityTest(String str){ setName(str); } public void run(){ for(int i=1; i<=5; i++){ System.out.println( i + getName() + " Priority : " + getPriority() ); }

10 장. 다중 스레드 19 Excercises ThreadPriority.java class ThreadPriority { public static void main(String args[]){ PriorityTest t1 = new PriorityTest(" : First Thread"); PriorityTest t2 = new PriorityTest(" : Second Thread"); PriorityTest t3 = new PriorityTest(" : Third Thread"); int priority_t1 = Integer.parseInt(args[0]); int priority_t2 = Integer.parseInt(args[1]); t1.setPriority(priority_t1); t2.setPriority(priority_t2); t3.setPriority(Thread.MIN_PRIORITY); t1.start(); t2.start(); t3.start(); }

10 장. 다중 스레드 20 1 : Third Thread : 1 1 : First Thread : 5 1 : Second Thread : 10 2 : Second Thread : 10 3 : Second Thread : 10 4 : Second Thread : 10 2 : First Thread : 5 3 : First Thread : 5 4 : First Thread : 5 5 : First Thread : 5 2 : Third Thread : 1 5 : Second Thread : 10 3 : Third Thread : 1 4 : Third Thread : 1 5 : Third Thread : 1

10 장. 다중 스레드 21

10 장. 다중 스레드 22 실습예제 DoubleThread1.java class DoubleThreadTest1 extends Thread { public DoubleThreadTest1(String str) { setName(str); } public void run() { for (int i=1 ; i<=3 ; i++) { System.out.println(i + getName()); } System.out.println(“End" + getName()); } public class DoubleThread1 { public static void main(String args[]) { DoubleThreadTest1 t1 = new DoubleThreadTest1(" : Thread1"); DoubleThreadTest1 t2 =

10 장. 다중 스레드 23 실습예제 DoubleThread1.java new DoubleThreadTest1(" : Thread2"); System.out.println("***** Start *****"); t1.start(); t2.start(); System.out.println("***** End *****"); }

10 장. 다중 스레드 24 ***** Start ***** ***** End ***** 1 : Thread2 1 : Thread1 2 : Thread2 2 : Thread1 3 : Thread2 3 : Thread1 End : Thread2 End : Thread1

10 장. 다중 스레드 5 스레드의 시작과 종료 25 실습예제 DoubleThread2.java class DoubleThreadTest2 extends Thread { public DoubleThreadTest2(String str) { setName(str); } public void run() { for (int i=1 ; i<=3 ; i++) { System.out.println(i + getName()); } System.out.println(“End" + getName()); } public class DoubleThread2 { public static void main(String args[])throws Exception { DoubleThreadTest2 t1 = new DoubleThreadTest2 (" : Thread1"); DoubleThreadTest2 t2 = new DoubleThreadTest2

10 장. 다중 스레드 26 실습예제 DoubleThread1.java (" : Thread2"); System.out.println("***** Start *****"); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("***** End *****"); }

10 장. 다중 스레드 27 ***** Start ***** 1 : Thread1 1 : Thread2 2 : Thread1 2 : Thread2 3 : Thread1 3 : Thread2 End : Thread1 End : Thread2 ***** End *****

10 장. 다중 스레드 28 synchronized Method 329 page Critical section unlock

10 장. 다중 스레드 page

10 장. 다중 스레드 30 Excercises TVContribution.java class Account { private int total = 0; synchronized void deposit() { total = total ; } int gettotal() { return total; } class Customer extends Thread { Account same_a; Customer(Account a, String s) { same_a = a; setName(s); } public void run() { for(int i = 0; i < 200 ; i++) { System.out.println(getName() + " : " + i);

10 장. 다중 스레드 31 실습예제 TVContribution.java same_a.deposit(); if (same_a.gettotal() >= ) break; } public class TVContribution { public static void main(String args[])throws Exception { Account same_account = new Account(); Customer donator1 = new Customer(same_account,“Donator1"); Customer donator2 = new Customer(same_account,"Donator2"); Customer donator3 = new Customer(same_account,"Donator3"); Customer donator4 = new Customer(same_account,"Donator4"); Customer donator5 = new Customer(same_account,"Donator5");

10 장. 다중 스레드 32 실습예제 TVContribution.java donator1.start(); donator2.start(); donator3.start(); donator4.start(); donator5.start(); donator1.join(); donator2.join(); donator3.join(); donator4.join(); donator5.join(); System.out.println(“Total : " + same_account.gettotal()); }

10 장. 다중 스레드 33 Donator3 : 0 Donator3 : 1 Donator1 : 0 Donator4 : Donator5 : 62 Donator3 : 124 Donator1 : 126 Donator4 : 125 Donator2 : 62 Total :

10 장. 다중 스레드 34 Donator1 : 0 Donator1 : 1 Donator1 : 2 Donator3 : Donator2 : 42 Donator3 : 102 Donator5 : 92 Donator1 : 62 Donator2 : 43 Total :

10 장. 다중 스레드 35 java.lang.Object Class - wait(), notify(), notifyAll() void wait() throws InterruptedException void wait(long msec) throws InterruptedException void wait(long msec, int nsec) throws InterruptedException void notify() void notifyAll()

10 장. 다중 스레드 36 wait( ), notify( ), notifyAll( ) Method 335 page

10 장. 다중 스레드 37 Excercises ProducerConsumer.java class Buffer { private int contents; private boolean available = false; public synchronized void put(int value) { while (available == true ) { try{ wait(); } catch (InterruptedException e) {} } contents = value; System.out.println (“Producer########## : Produce " + contents); notify(); available = true; } public synchronized int get() { while (available == false ) { try { wait();

10 장. 다중 스레드 38 Excercises ProducerConsumer.java } catch (InterruptedException e) {} } System.out.println (“Consumer########## : Consume " + contents); notify(); available = false; return contents; } class Producer extends Thread { private Buffer b; public Producer(Buffer blank) { b = blank ; } public void run() { for (int i = 1; i <= 10;i++) b.put(i); }

10 장. 다중 스레드 39 Excercises ProducerConsumer.java class Consumer extends Thread { private Buffer b; public Consumer(Buffer blank) { b = blank; } public void run() { int value = 0; for (int i = 1 ; i <= 10 ; i++ ) value = b.get(); } public class ProducerConsumer { public static void main(String args[]) { Buffer buff = new Buffer(); Producer p1 = new Producer(buff); Consumer c1 = new Consumer(buff); p1.start() ; c1.start() ; }

10 장. 다중 스레드 40 Producer ########## : Produce 0 Consumer########## : Consume 0 Producer ########## : Produce Consumer########## : Consume 7 Producer ########## : Produce 8 Consumer########## : Consume 8 Producer ########## : Produce 9 Consumer########## : Consume 9