Skip to content
Snippets Groups Projects
03-ExampleThread.java 1.29 KiB
Newer Older
//    PDF: https://moodle.epfl.ch/pluginfile.php/3175938/mod_folder/content/0/week01-3-Introduction-to-Threads-2-with-Demo.pdf
//  Video: https://mediaspace.epfl.ch/playlist/dedicated/31866/0_c46icdbx/0_zx4gncsb
// Slides: 4

package lecture1;

/** An example Thread implementation in Java. */
class ExampleThread extends Thread {
	int sleepiness;

	public void run() {
		int i = 0;
		while (i < 8) {
			System.out.println(getName() + " has counter " + i);
			i++;
			try {
				sleep(sleepiness);
			} catch (InterruptedException e) {
				System.out.println("Thread was interrupted.");
			}
		}
	}

	// Run from the SBT shell with `runMain lecture1.ExampleThread`.
	public static void main(String[] args) {
		ExampleThread t1 = new ExampleThread();
		t1.sleepiness = 2;
		ExampleThread t2 = new ExampleThread();
		t2.sleepiness = 3;
		System.out.println("Little threads did not start yet!");
		t1.start();
		t2.start();
		System.out.println("Parent thread running!");
		try {
			sleep(29);
		} catch (InterruptedException e) {
			System.out.println("Parent thread was interrupted.");
		}
		System.out.println("Parent thread running!");
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			System.out.println("A thread was interrupted!");
		}
		System.out.println("Done executing thread.");
	}
}