1 of 10

Introduction to multithreading and thread synchronization

Dr. Noman Islam

2 of 10

Introduction

  • A thread is an independent unit of execution.
  • A thread is also called a light-weight process
  • A program may contain multiple threads
  • Each of the thread may have local variables and its context, that are maintained by operating system for each thread

3 of 10

Multithreading in Java

  • In Java, the Runnable interface and Thread class of package java.lang are used for implementation of thread
  • To implement a thread, the desired class must implement the Runnable interface and provide the run() method.

public class MyThread implements Runnable {

public void run() {

//implementation of thread�}

}

4 of 10

  • The Thread class can then be used to start a thread as follows:

public class TestThread

{

public static void main( String[] args )

{

MyThread m = new MyThread();

Thread t = new Thread(m);

m.start();

}

}

5 of 10

Exercises

  • Write a class that implements Runnable.
  • Define a constructor that takes the name of the thread as argument.
  • The thread upon execution will print the name of the thread in a while loop.
  • Define and run 5 thread objects. What output do you see?
  • In above task, modify the run method to randomly sleep the thread for few milliseconds. Observe the output.

6 of 10

Synchronization in Java

7 of 10

An example without synchronization

public class UnsynchronizedExample {

public static void main(String[] args) {

new PrintStringsThread("Hello ", "there.");

new PrintStringsThread("How are ", "you?");

new PrintStringsThread("Thank you ", "very much!");

}

}

8 of 10

public class PrintStringsThread implements Runnable {

Thread thread;

String str1, str2;

PrintStringsThread(String str1, String str2) {

this.str1 = str1;

this.str2 = str2;

thread = new Thread(this);

thread.start();

}

public void run() {

TwoStrings.print(str1, str2);

}

}

9 of 10

public class TwoStrings {

// This method is not synchronized

static void print(String str1, String str2) {

System.out.print(str1);

try {

Thread.sleep(500);

} catch (InterruptedException ie) {

}

System.out.println(str2);

}

}

10 of 10

Exercises

  1. What output do you see? Explain the output.
  2. Now use the synchronized methods to display the desired result.
  3. Now use the synchronized keyword on an object to synchronize.