0

I want to create and start 5 java threads. The threads should display message then stop execution. Am I doing this correctly or not?

public class HelloThread extends Thread {
    private String thread_name;

    // constructor
    HelloThread(String tname) {
        thread_name = new String(tname);
    }

    // override method run()
    public void run() {
        setName(thread_name);
        System.out.println(" Thread " + thread_name); //assigning each thread a name 
    }

    public static void main(String args[]) {
        for (int i = 1; i < 6; i++) {
            HelloThread mythr_obj = new HelloThread(i + " says Hello World!!! ");
            mythr_obj.start(); // start execution of the thread object
        }
    }
}
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
  • 1
    There's no need for `new String(tname)`, why do you want to make a copy of the string? Otherwise, are you doing it correctly? Well, does it do what you expect it to do? I mean, it's only a "Hello World" style program, there isn't much design-wise you could do wrong. – ci_ Sep 09 '15 at 13:32
  • If this code actually compiles, I would recommend asking on codereview.stackexchange.com, as the possible answers are probably too broad/opinion based for here. – Andy Brown Sep 09 '15 at 13:32
  • @AndyBrown This isn't really on topic for Code Review as it looks like the post just contains example code. Even if that compiles and runs it's off topic as CR is for reviewing real code. – SuperBiasedMan Sep 09 '15 at 13:34
  • @SuperBiasedMan - fair enough, although we now know what the real question is: "*I'm not sure if its creating multiple threads or just creating one at a time then stopping*", so the nature of this has changed somewhat. – Andy Brown Sep 09 '15 at 13:37
  • You won't see the printouts because you are not waiting for the trhreads to complete. You need to use `Thread.join()` on each thread so you will need to keep hold of them in a list or something. – OldCurmudgeon Sep 09 '15 at 13:37
  • 2
    @OldCurmudgeon - they aren't daemon threads, so [the JVM will wait until they complete](http://stackoverflow.com/a/9651919/1945631) and the printlns will be seen. – Andy Brown Sep 09 '15 at 13:43

3 Answers3

2

Since the introduction of the java.util.concurrent libraries in java 1.4, developers rarely create their own Thread instances these days.

Today, you're more likely to do

ExecutorService threadPool = Executors.newFixedThreadPool(5);

List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 20; ++ i) {
    Callable<Integer> callable = () -> {
        TimeUnit.SECONDS.sleep(1);
        System.out.println("Returning " + i);
        return i;
    };
    Future<Integer> future = threadPool.submit(callable);
    futures.add(future);
}
for (Future<Integer> future : futures) {
    Integer result = future.get();
    System.out.println("Finished " + result);
}

threadPool.shutdown();
lance-java
  • 25,497
  • 4
  • 59
  • 101
1

Have you tried compiling and running this code? It looks correct, although I would recommend having your main method in a separate class.

F. Stephen Q
  • 4,208
  • 1
  • 19
  • 42
  • Yes it works but I was just curious about starting the threads in the loop. I'm not sure if its creating multiple threads or just creating one at a time then stopping. – golferdrew32 Sep 09 '15 at 13:33
  • 1
    @golferdrew32 - I suggest you ask that exact question instead of a question that doesn't state what you want to know. – Andy Brown Sep 09 '15 at 13:36
  • @golferdrew32: Whenever `start()` is called, a new thread spins off and the old thread continues on. What you're doing is an entirely valid, and in fact fairly standard, way of starting threads. Try putting something like `sleep(Random.getInt())` in your `run()` method to see this more visibly illustrated. – F. Stephen Q Sep 09 '15 at 13:37
  • @golferdrew32 It is creating multiple threads, that can easily be seen if you add `System.out.println("Thread started");` inside that loop, and see the order the messages are printed in. – Simon Forsberg Sep 09 '15 at 13:38
0

Yes. You did it well but as @FSQ suggested, your whole class is itself a thread. You may put the main method in any other class.

CodeRunner
  • 687
  • 5
  • 13