Introduction to multithreading and thread synchronization
Dr. Noman Islam
Introduction
Multithreading in Java
public class MyThread implements Runnable {
public void run() {
//implementation of thread�}
}
public class TestThread
{
public static void main( String[] args )
{
MyThread m = new MyThread();
Thread t = new Thread(m);
m.start();
}
}
Exercises
Synchronization in Java
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!");
}
}
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);
}
}
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);
}
}
Exercises