// Sample code showing a multithreaded hello-world in java.

// A runnable object which contains the actual code executed by the threads
class SomeRunnable implements Runnable {

    // number of messages to emit before exiting
    public static final int N = 20; 
    // amount of time to wait between messages
    public static final int T = 100;

    // the string it will emit
    private String myText;

    SomeRunnable(String s) {
        myText = s;
    }

    // this is the method that the thread will execute once started.
    // it simply emits N messages, sleeping for Tms between.
    public void run() {
        for (int i=0;i<N;i++) {
            try {
                Thread.sleep(T);
            } catch(InterruptedException ie) {
                // it's not really a problem if we don't sleep for 
                // the entire time because of an interrupt
            }
            System.out.println(myText);
        }
    }
}


public class BasicThreadExample {

    public static void main(String[] args) {
        Thread t1,t2;
        
        System.out.println("Starting threads...");
        // create 2 threads with different messages.  these threads
        // will run concurrently, probably interleaving their output
        t1 = new Thread(new SomeRunnable("Hello world!"));
        t2 = new Thread(new SomeRunnable("Bonjour monde!"));
        
        // now, get both threads to actually start
        t1.start();
        t2.start();

        // and wait for them both to finish.  You don't have to do
        // this, but it shows how to use join.
        // notice that we again ignore InterruptedExceptions---that's
        // because in this case everything would work whether or not 
        // we finished the join operation.
        try {
            t1.join();
        } catch(InterruptedException ie) { }
        try {
            t2.join();
        } catch(InterruptedException ie) { }
        System.out.println("All done!");
    }
}
