Skip to content

Instantly share code, notes, and snippets.

@kikoso
Last active December 7, 2016 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kikoso/5fc049be17ec3a055ee93f9ec47ecdba to your computer and use it in GitHub Desktop.
Save kikoso/5fc049be17ec3a055ee93f9ec47ecdba to your computer and use it in GitHub Desktop.
class PrintDemo {
private int i;
public void printCount() {
try {
for (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() {
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