Skip to content

Instantly share code, notes, and snippets.

@markojerkic
Created April 20, 2017 09:31
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 markojerkic/6292687990f671fc02324886c07be66b to your computer and use it in GitHub Desktop.
Save markojerkic/6292687990f671fc02324886c07be66b to your computer and use it in GitHub Desktop.
A simple java program that shows how to implement the Runnable interface
class MyThread implements Runnable {
Thread thrd;
MyThread (String thrdName) {
thrd = new Thread(this, thrdName); //constructor
thrd.start(); //starts the thread
}
//run() is the only method that you must override
public void run() {
System.out.println(thrd.getName() + " starting.");
try {
for(int i = 0; i < 10000; i++) {
Thread.sleep(40); //sets the thread to wait for 40 miliseconds
//throws InterruptedException
System.out.println("In " + thrd.getName() + " count is " + i);
}
} catch(InterruptedException e) {
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " terminating.");
}
}
class SimpleThread {
public static void main(String args[]) {
MyThread thrd1 = new MyThread("Thread#1");
MyThread thrd2 = new MyThread("Thread#2");
MyThread thrd3 = new MyThread("Thread#3");
thrd1.thrd.setPriority(Thread.MAX_PRIORITY); //sets the priority to 10
thrd3.thrd.setPriority(Thread.MIN_PRIORITY); //sets the priority to 1
try{
thrd1.thrd.join(); //joins the thread to the main thread
thrd2.thrd.join(); //joins the thread to the main thread
thrd3.thrd.join(); //joins the thread to the main thread
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println("Main thread ending.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment