Created
April 20, 2017 09:55
-
-
Save markojerkic/9c67862ee3122d237451c14b6dd5e6f2 to your computer and use it in GitHub Desktop.
Extending the Thread class
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 MyThread extends Thread { | |
MyThread (String thrdName) { | |
super(thrdName); //constructor | |
start(); //starts the thread | |
} | |
//run() is the only method that you must override | |
public void run() { | |
System.out.println(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 " + getName() + " count is " + i); | |
} | |
} catch(InterruptedException e) { | |
System.out.println(getName() + " interrupted."); | |
} | |
System.out.println(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.setPriority(Thread.MAX_PRIORITY); //sets the priority to 10 | |
thrd3.setPriority(Thread.MIN_PRIORITY); //sets the priority to 1 | |
try{ | |
thrd1.join(); | |
thrd2.join(); | |
thrd3.join(); | |
} 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