Created
May 3, 2019 05:24
-
-
Save Gumball12/c7d29a4ed72eb695bef45d7486f0a337 to your computer and use it in GitHub Desktop.
os assignment: java thread
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
// https://repl.it/@Gumball12/os-assignment-java-thread | |
// import modules | |
import java.lang.Thread; | |
import java.lang.Math; | |
import java.lang.InterruptedException; | |
// ThreadTester class | |
public class ThreadTester { | |
public static void main (String[] args) { | |
// create PrintThread instances with name | |
PrintThread pt1 = new PrintThread("thread1"); | |
PrintThread pt2 = new PrintThread("thread2"); | |
PrintThread pt3 = new PrintThread("thread3"); | |
System.out.println("Starting threads"); | |
// starting threads | |
pt1.start(); | |
pt2.start(); | |
pt3.start(); | |
System.out.println("Threads started, main ends\n"); | |
// main-thread end | |
} | |
} | |
// PrintThread class | |
class PrintThread extends Thread { | |
// sleep time | |
private int sleep; | |
// constructor | |
public PrintThread (String name) { | |
super(name); | |
sleep = (int) (Math.random() * 5001); | |
} | |
// thread run | |
public void run () { | |
try { | |
System.out.println(getName() + " going to sleep for " + sleep + " ms"); | |
Thread.sleep(sleep); // sleep | |
} catch (InterruptedException ex) { | |
ex.printStackTrace(); | |
} | |
System.out.println(getName() + " done sleeping");\ | |
// sub-thread end | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment