Last active
February 3, 2018 22:17
-
-
Save rishabh-ink/17819e3aac9a46ed3cf06f467ffc2621 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
threadsynch; | |
class Printer | |
{ | |
synchronized void printThis(Thread t, String text) | |
{ | |
System.out.println("My thread ID: " + t); | |
/* let the current thread sleep */ | |
/* so that the thread-scheduler context-switches */ | |
/* to another thread, introducing a race condition */ | |
try | |
{ | |
Thread.sleep(100); | |
} | |
catch(InterruptedException exp) | |
{ | |
System.out.println("INTERRUPTED: Thread.sleep()"); | |
} | |
/* now print the string */ | |
System.out.println("My payload: " + text); | |
} | |
} | |
class ThreadCreator implements Runnable | |
{ | |
String txt; | |
Printer dest; | |
Thread thr; | |
/* Initialize and create the threads */ | |
public ThreadCreator(Printer d, String t) | |
{ | |
dest = d; | |
txt = t; | |
thr = new Thread(this); | |
thr.start(); | |
} | |
public void run() | |
{ | |
dest.printThis(thr, txt); | |
} | |
} | |
public class Main | |
{ | |
public static void main(String[] args) | |
{ | |
/* Creator */ | |
Printer destination = new Printer(); | |
/* Create 4 sample threads */ | |
ThreadCreator tc1 = new ThreadCreator(destination, "the quick"); | |
ThreadCreator tc2 = new ThreadCreator(destination, "brown fox"); | |
ThreadCreator tc3 = new ThreadCreator(destination, "jumps over"); | |
ThreadCreator tc4 = new ThreadCreator(destination, "the lazy dog"); | |
/* Wait for all threads to join */ | |
try | |
{ | |
tc1.thr.join(); | |
tc2.thr.join(); | |
tc3.thr.join(); | |
tc4.thr.join(); | |
} | |
catch(InterruptedException exp) | |
{ | |
System.out.println("INTERRUPTED: Thread.join()"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment