09 MultiThreadedProgramming
09 MultiThreadedProgramming
Week 9: Multithreaded
Programming
Lecturer: NGUYỄN Thị Minh Tuyền
Plan 2
1. Multithreading fundamentals
2. Synchronization
Java Programming
Plan 3
1. Multithreading fundamentals
2. Synchronization
Java Programming
Multithreading fundamentals 4
Java Programming
Advantage of multithreading 5
Java Programming
Thread class and Runnable
interface 7
Java Programming
Creating a thread [1] 8
Java Programming
Creating a thread [2] 9
Java Programming
Creating a thread [3] 10
Java Programming
11
Java Programming
1. class MyThread implements Runnable {
2.
3.
String thrdName;
MyThread(String name) {
12
4. thrdName = name;
5. }
6. // Entry point of thread.
7. public void run() {
8. System.out.println(thrdName + " starting.");
9. try {
10. for (int count = 0; count < 10; count++) {
11. Thread.sleep(400);
12. System.out.println("In " + thrdName +
13. ", count is " + count);
14. }
15. } catch (InterruptedException exc) {
16. System.out.println(thrdName + " interrupted.");
17. }
18. System.out.println(thrdName + " terminating.");
19. }
Java Programming
20. }
1. class UseThreads {
2. public static void main(String args[]) { 13
3. System.out.println("Main thread starting.");
4. // First, construct a MyThread object.
5. MyThread mt = new MyThread("Child #1");
6. // Next, construct a thread from that object.
7. Thread newThrd = new Thread(mt);
8. // Finally, start execution of the thread.
9. newThrd.start();
10. for (int i = 0; i < 50; i++) {
11. System.out.print(".");
12. try {
13. Thread.sleep(100);
14. } catch (InterruptedException exc) {
15. System.out.println("Main thread interrupted.");
16. }
17. }
18. System.out.println("Main thread ending.");
19. }
Java Programming
20. }
14
Java Programming
1. class MyThread12 implements Runnable{
2. Thread thrd;
3. MyThread12(String name){ thrd = new Thread(this, name); }
4. public static MyThread12 createAndStart(String name) {
5. MyThread12 myThrd = new MyThread12(name);
myThrd.thrd.start(); // start the thread
6.
7. return myThrd; Improved
8.
9.
}
@Override
version
10. public void run() {
11. System.out.println(thrd.getName() + " starting.");
12. try {
13. for(int count = 0; count < 10; count++) {
14. Thread.sleep(400);
15. System.out.println("In " + thrd.getName() +
16. ", count is " + count);
17. }
18. }catch(InterruptedException exc) {
19. System.out.println(thrd.getName() + " interrupted.");
20. }
21. System.out.println(thrd.getName() + " terminating.");
22. }
Java Programming
23. }
16
Java Programming
1. class MyThread2 implements Runnable {
2.
3.
Thread thrd;
MyThread2(String name) {
20
4. thrd = new Thread(this, name); thrd.start();
5. }
6. public void run() {
7. System.out.println(thrd.getName() + " starting.");
8. try {
9. for (int count = 0; count < 10; count++) {
10. Thread.sleep(400);
11. System.out.println("In " + thrd.getName()
12. + ", count is " + count);
13. }
14. } catch (InterruptedException exc) {
15. System.out.println(thrd.getName()
16. + " interrupted.");
17. }
18. System.out.println(thrd.getName() + " terminating.");
19. }
Java Programming
20. }
1. class MoreThreads {
2. public static void main(String args[]) { 21
3. System.out.println("Main thread starting.");
4.
5. MyThread2 mt1 = new MyThread2("Child #1");
6. MyThread2 mt2 = new MyThread2("Child #2");
7. MyThread2 mt3 = new MyThread2("Child #3");
8.
9. for (int i = 0; i < 50; i++) {
10. System.out.print(".");
11. try {
12. Thread.sleep(100);
13. } catch (InterruptedException exc) {
14. System.out.println("Main thread interrupted.");
15. }
16. }
17. System.out.println("Main thread ending.");
18. }
Java Programming
19. }
22
Java Programming
Determining when a thread ends 23
Java Programming
1. class MoreThreads {
2. /* version 2*/ 24
3. public static void main(String args[]) {
4. System.out.println("Main thread starting.");
5. MyThread2 mt1 = new MyThread2("Child #1");
6. MyThread2 mt2 = new MyThread2("Child #2");
7. MyThread2 mt3 = new MyThread2("Child #3");
8. do {
9. System.out.print(".");
10. try { Thread.sleep(100);
11. }catch(InterruptedException exc) {
12. System.out.println("Main thread interrupted.");
13. }
14. } while (mt1.thrd.isAlive() ||
15. mt2.thrd.isAlive() ||
16. mt3.thrd.isAlive());
17. System.out.println("Main thread ending.");
18. }
Java Programming
19. }
1. class MyThread3 implements Runnable {
2.
3.
Thread thrd;
MyThread3(String name) {
25
4. thrd = new Thread(this, name);thrd.start();
5. }
6. public void run() {
7. System.out.println(thrd.getName() + " starting.");
8. try {
9. for (int count = 0; count < 10; count++) {
10. Thread.sleep(400);
11. System.out.println("In " + thrd.getName()
12. + ", count is " + count);
13. }
14. } catch (InterruptedException exc) {
15. System.out.println(thrd.getName()
16. + " interrupted.");
17. }
18. System.out.println(thrd.getName() + " terminating.");
19. }
20. } Java Programming
1. class JoinThreads {
2.
3.
public static void main(String args[]) {
System.out.println("Main thread starting.");
26
4. MyThread3 mt1 = new MyThread3("Child #1");
5. MyThread3 mt2 = new MyThread3("Child #2");
6. MyThread3 mt3 = new MyThread3("Child #3");
7. try {
8. mt1.thrd.join();
9. System.out.println("Child #1 joined.");
10. mt2.thrd.join();
11. System.out.println("Child #2 joined.");
12. mt3.thrd.join();
13. System.out.println("Child #3 joined.");
14. } catch (InterruptedException exc) {
15. System.out.println("Main thread interrupted.");
16. }
17. System.out.println("Main thread ending.");
18. }
19. }
Java Programming
27
Java Programming
Thread priorities 28
Java Programming
29
Java Programming
1. class Priority implements Runnable {
2. int count; Thread thrd; 30
3. static boolean stop = false; static String currentName;
4. Priority(String name) {
5. thrd = new Thread(this, name); count = 0;
6. currentName = name;
7. }
8. public void run() {
9. System.out.println(thrd.getName() + " starting.");
10. do { count++;
11. if (currentName.compareTo(thrd.getName()) != 0) {
12. currentName = thrd.getName();
13. System.out.println("In " + currentName);
14. }
15. } while (stop == false && count < 10000000);
16. stop = true;
17. System.out.println("\n" + thrd.getName()
18. + " terminating.");
19. }
Java Programming
20. }
1. class PriorityDemo {
2. public static void main(String args[]) { 31
3. Priority mt1 = new Priority("High Priority");
4. Priority mt2 = new Priority("Low Priority");
5. Priority mt3 = new Priority("Normal Priority #1");
6. Priority mt4 = new Priority("Normal Priority #2");
7. Priority mt5 = new Priority("Normal Priority #3");
8. mt1.thrd.setPriority(Thread.NORM_PRIORITY + 2);
9. mt2.thrd.setPriority(Thread.NORM_PRIORITY - 2);
10. mt1.thrd.start(); mt2.thrd.start();
11. mt3.thrd.start(); mt4.thrd.start(); mt5.thrd.start();
12. try {
13. mt1.thrd.join(); mt2.thrd.join();
14. mt3.thrd.join(); mt4.thrd.join(); mt5.thrd.join();
15. } catch (InterruptedException exc) {
16. System.out.println("Main thread interrupted.");
17. }
Java Programming
18. ....
32
1. ...
2. System.out.println("\nHigh priority thread counted to
3. " + mt1.count);
Java Programming
Plan 33
1. Multithreading fundamentals
2. Synchronization
Java Programming
Synchronization [1] 34
Java Programming
Synchronized methods 36
Java Programming
1. class SumArray {
2. private int sum; 37
3. synchronized int sumArray(int nums[]) {
4. sum = 0; // reset sum
5. for (int i = 0; i < nums.length; i++) {
6. sum += nums[i];
7. System.out.println("Running total for "
8. + Thread.currentThread().getName()
9. + " is " + sum);
10. try {
11. Thread.sleep(10); // allow task-switch
12. } catch (InterruptedException exc) {
13. System.out.println("Thread interrupted.");
14. }
15. }
16. return sum;
17. }
Java Programming
18. }
1. class MyThread4 implements Runnable {
2. Thread thrd; 38
3. static SumArray sa = new SumArray();
4. int a[]; int answer;
5. MyThread4(String name, int nums[]) {
6. thrd = new Thread(this, name);
7. a = nums; thrd.start(); // start the thread
8. }
9. public void run() {
10. int sum;
11. System.out.println(thrd.getName() + " starting.");
12. answer = sa.sumArray(a);
13. System.out.println("Sum for " + thrd.getName()
14. + " is " + answer);
15. System.out.println(thrd.getName() + " terminating.");
16. }
17. }
Java Programming
39
1. class Sync {
2. public static void main(String args[]) {
3. int a[] = { 1, 2, 3, 4, 5 };
4. MyThread4 mt1 = new MyThread4("Child #1", a);
5. MyThread4 mt2 = new MyThread4("Child #2", a);
6.
7. try {
8. mt1.thrd.join();
9. mt2.thrd.join();
10. } catch (InterruptedException exc) {
11. System.out.println("Main thread interrupted.");
12. }
13. }
14. } Java Programming
40
Java Programming
Synchronized statement 41
Java Programming
42
synchronized(objref) {
// statements to be synchronized
}
Java Programming
1. class SumArray1 {
2. private int sum; 43
3. int sumArray1(int nums[]) {
4. sum = 0; // reset sum
5. for (int i = 0; i < nums.length; i++) {
6. sum += nums[i];
7. System.out.println("Running total for "
8. + Thread.currentThread().getName()
9. + " is " + sum);
10. try {
11. Thread.sleep(10); // allow task-switch
12. } catch (InterruptedException exc) {
13. System.out.println("Thread interrupted.");
14. }
15. }
16. return sum;
17. }
Java Programming
18. }
1. class MyThread5 implements Runnable {
2. Thread thrd; 44
3. static SumArray sa = new SumArray();
4. int a[]; int answer;
5. MyThread5(String name, int nums[]) {
6. thrd = new Thread(this, name);
7. a = nums; thrd.start(); // start the thread
8. }
9. public void run() {
10. int sum;
11. System.out.println(thrd.getName() + " starting.");
12. // synchronize calls to sumArray()
13. synchronized (sa) { answer = sa.sumArray(a); }
14. System.out.println("Sum for " + thrd.getName()
15. + " is " + answer);
16. System.out.println(thrd.getName() + " terminating.");
17. }
Java Programming
18. }
45
1. class Sync1 {
2. public static void main(String args[]) {
3. int a[] = { 1, 2, 3, 4, 5 };
4. MyThread5 mt1 = new MyThread5("Child #1", a);
5. MyThread5 mt2 = new MyThread5("Child #2", a);
6.
7.
try {
8.
mt1.thrd.join();
9. mt2.thrd.join();
11.
System.out.println("Main thread interrupted.");
12.
}
13. }
Java Programming
47
1. class ThreadCom {
2. public static void main(String args[]) {
3. TickTock tt = new TickTock();
4. MyThread6 mt1 = new MyThread6("Tick", tt);
5. MyThread6 mt2 = new MyThread6("Tock", tt);
6.
7. try {
8. mt1.thrd.join();
9. mt2.thrd.join();
10. } catch (InterruptedException exc) {
11. System.out.println("Main thread interrupted.");
12. }
13. }
14. } Java Programming
Deadlock, race condition 51
Java Programming
Suspending, resuming, and
stopping threads 52
Java Programming
1. class MyThread8 implements Runnable {
2.
3.
Thread thrd; boolean suspended; boolean stopped;
MyThread8(String name) {
53
4. thrd = new Thread(this, name);
5. suspended = false; stopped = false; thrd.start();
6. }
7. public void run() {
8. System.out.println(thrd.getName() + " starting.");
9. try {
10. for (int i = 1; i < 1000; i++) {
11. System.out.print(i + " ");
12. if ((i % 10) == 0) {
13. System.out.println(); Thread.sleep(250);
14. }
15. synchronized (this){
16. while(suspended){wait();}
17. if(stopped) break;
18. }
Java Programming
19. }
1. } catch (InterruptedException exc) {
2.
54
System.out.println(thrd.getName() + " interrupted.");
3. }
4. System.out.println(thrd.getName() + " exiting.");
5. }
6. synchronized void mystop() {
7. stopped = true;
8. suspended = false;
9. notify();
10. }
11. synchronized void mysuspend() {
12. suspended = true;
13. }
14. synchronized void myresume() {
15. suspended = false;
16. notify();
17. }
Java Programming
18. }
1. class Suspend {
2. public static void main(String args[]) { 55
3. MyThread8 ob1 = new MyThread8("My Thread");
4. try {
5. Thread.sleep(1000);
6. //let ob1 thread start executing
7. ob1.mysuspend();
8. System.out.println("Suspending thread.");
9. Thread.sleep(1000);
10.
11.
ob1.myresume();
12.
System.out.println("Resuming thread.");
13. Thread.sleep(1000);
14.
15.
ob1.mysuspend();
16.
System.out.println("Suspending thread.");
17. Thread.sleep(1000);
Java Programming
1. ob1.myresume();
2. System.out.println("Resuming thread."); 56
3. Thread.sleep(1000);
4.
5. ob1.mysuspend();
6. System.out.println("Stopping thread.");
7. ob1.mystop();
8. } catch (InterruptedException e) {
9. System.out.println("Main thread Interrupted");
10. }
11. try {
12. ob1.thrd.join();
13. } catch (InterruptedException e) {
14. System.out.println("Main thread Interrupted");
15. }
16. System.out.println("Main thread exiting.");
17. }
Java Programming
18. }