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:
He's doing multithreading like this:
class MyThread implements Runnable {
Thread t;
MyThread() {
t = new Thread(this, "Demo");
t.start();
}
public void run() {
try {
for (int i = 5; i > 0; i--) {
System.out.println("Child-Thread:" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted");
}
System.out.println("Child finished");
}
}
I find it cleaner doing like this:
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 > 0; i--) {
System.out.println("Thread " + number + ": " + i);
}
}
}
}
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.
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.
Thanks!
ScheduledExecutorService. Does it support interrupting sleeping threads?