001    //package edu.unima.ky.parallel;
002    
003    /** 
004     * Hallo Welt Thread.
005     * Multi threaded application processing and displaying "names" from 
006     * threads while threads are sleeping for a random time.
007     * @author Heinz Kredel. 
008     */ 
009    public class HalloWeltThread {
010    
011        public static void main(String[] args) {
012    
013            String name = "Kily";
014            if (args.length > 0 ) {
015                name = args[0];
016            }
017    
018            for (int i = 0; i < 1; i++ ) {
019                System.out.println("Creating Threads ... ");
020                Thread t1 = new Thread( new Tuwas("Michael") );
021                Thread t2 = new Thread( new Tuwas("Karl") );
022                Thread t3 = new Thread( new Tuwas(name) );
023    
024                System.out.println("Starting Threads ... ");
025                t1.start(); t2.start(); t3.start(); 
026    
027                System.out.println("Waiting on Threads to terminate ... ");
028                /*  test ohne join */
029                try {
030                    t1.join(); t2.join(); t3.join(); 
031                } catch(Exception e) { 
032                  System.out.println("Dies sollte nicht passieren "+e);
033                }
034                /*   */
035                System.out.println("Threads joined");
036                //System.exit(0); // test
037            }
038        }
039    
040    }
041    
042    /**
043     * Object to be executed in a Thread. 
044     */
045    class Tuwas implements Runnable {
046    
047        String var = "";
048    
049    /** 
050     * Konstructor.
051     * @param v A String, the desired name.
052     */
053        public Tuwas(String v) {
054            var = v;
055        }
056    
057    /** 
058     * Runs five times per thread but sleeping a random time.
059     */
060         public void run() {
061            for (int k = 0; k < 5; k++) {
062                Work.schaffen(100);
063                System.out.println("Hi " + var + " zum " + k + "-ten");      
064            }
065        }
066    
067    }
068    
069    /**
070     * Random delay by working.
071     */
072    class Work {
073    
074    /** 
075     * Random delay.
076     * @param max the desired delay in ms.
077     */
078        public static void schaffen(int max) {
079            try {
080                Thread.currentThread().sleep( (int)(max*Math.random()) );
081            } catch (InterruptedException e) {
082                  System.out.println("Dies sollte nicht passieren "+e);
083            }
084    
085        }
086    
087    }