Skip to content
Snippets Groups Projects
04-using-threads.java 1.2 KiB
Newer Older
// Lecture 1 : 14/15
package lecture1;

class ExampleThread extends Thread {
    int sleepiness;
    public void run() {
        int i = 0;
        while (i < 8) {
            System.out.println("Thread" + getName() + " has counter " + i);
            i++;
            try {sleep(sleepiness);}
            catch (InterruptedException e) {
                System.out.println("Thread was interrupted.");
            }
        }
    }
    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 interruped!");
        }
        System.out.println("Done executing thread.");
    }
}