Skip to content

Instantly share code, notes, and snippets.

@Gumball12
Created May 3, 2019 05:24
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 Gumball12/c7d29a4ed72eb695bef45d7486f0a337 to your computer and use it in GitHub Desktop.
Save Gumball12/c7d29a4ed72eb695bef45d7486f0a337 to your computer and use it in GitHub Desktop.
os assignment: java thread
// 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