Last active
December 7, 2016 12:44
-
-
Save kikoso/8f60f16c5db335aa7c7d8ee36e3de996 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
class PrintDemo { | |
public void printCount() { | |
try { | |
for (int i = 5; i > 0; i--) { | |
System.out.println("Selected number is: " + i ); | |
} | |
} catch (Exception e) { | |
System.out.println("Thread has been interrupted."); | |
} | |
} | |
} | |
class ThreadDemo implements Runnable { | |
private Thread thread; | |
private String threadName; | |
PrintDemo printDemo; | |
ThreadDemo(String threadName, PrintDemo printDemo) { | |
this.threadName = threadName; | |
this.printDemo = printDemo; | |
} | |
public void run() { | |
synchronized(printDemo) { | |
printDemo.printCount(); | |
} | |
System.out.println("Thread " + threadName + " finishing."); | |
} | |
public void start () { | |
System.out.println("Starting " + threadName); | |
if (thread == null) { | |
thread = new Thread (this, threadName); | |
thread.start (); | |
} | |
} | |
} | |
public class Example { | |
public static void main(String args[]) { | |
PrintDemo printDemo = new PrintDemo(); | |
ThreadDemo firstThread = new ThreadDemo("Thread 1", printDemo); | |
ThreadDemo secondThread = new ThreadDemo("Thread 2", printDemo); | |
try { | |
firstThread.start(); | |
secondThread.start(); | |
} catch( Exception e) { | |
System.out.println("Interrupted"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment