Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Multithreading - Best practice
    text
    copied!<p>I'm having trouble at understanding out teachers' method of multithreading. Well, before showing both our examples I must say he's teaching a bunch of newbies (including me I guess ^.^) so he might have picked a method of multithreading that's easy to understand. Also, I'm not visiting his classes, but I've got his script which says the following:</p> <p>He's doing multithreading like this:</p> <pre><code>class MyThread implements Runnable { Thread t; MyThread() { t = new Thread(this, "Demo"); t.start(); } public void run() { try { for (int i = 5; i &gt; 0; i--) { System.out.println("Child-Thread:" + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Child interrupted"); } System.out.println("Child finished"); } } </code></pre> <p>I find it cleaner doing like this:</p> <pre><code>public class Aufg1 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub MyThread t1 = new MyThread(1); ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); executor.schedule(t1, 1, TimeUnit.SECONDS); } static class MyThread implements Runnable { int number; public MyThread(int number) { this.number = number; } @Override public void run() { // TODO Auto-generated method stub for (int i = 5; i &gt; 0; i--) { System.out.println("Thread " + number + ": " + i); } } } } </code></pre> <p>Don't bother why I used a Thread-Pool of size 5. I needed it for another exercise. Also, I could've used a ThreadPool for a single execution is this example.</p> <p>Is there a big difference? Is there an even cleaner way? I know there're some other methods to multithread as well, though I only showed one in here.</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload