Java Multithreading: Starting Threads
Does multithreading seem like a black art to you? This is
the first part of an advanced Java tutorial on multithreading that hopefully
will help you out. In this tutorial we look at the two ways of starting a
thread in Java.
This is an advanced tutorial, and as such I assume that
you’re OK with extending classes, implementing interfaces and so on.
Code Examples For This Tutorial
Starting threads by extending the Thread class:
class Runner extends Thread {
@Override
public void run() {
for(int i=0; i<5;
i++) {
System.out.println("Hello:
" + i);
try {
Thread.sleep(100);
} catch
(InterruptedException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Application
{
public static void main(String[]
args) {
Runner runner1 = new Runner();
runner1.start();
Runner runner2 = new Runner();
runner2.start();
}
}
Starting threads using
Runnable interface:
class Runner implements Runnable {
@Override
public void run() {
for(int i=0; i<5;
i++) {
System.out.println("Hello:
" + i);
try {
Thread.sleep(100);
} catch
(InterruptedException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Application
{
public static void main(String[]
args) {
Thread thread1 = new Thread(new Runner());
thread1.start();
}
}
Starting threads
using the Thread constructor with anonymous classes:
public class Application
{
public static void main(String[]
args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<5;
i++) {
System.out.println("Hello:
" + i);
try {
Thread.sleep(100);
} catch
(InterruptedException e) {
// TODO
Auto-generated catch block
e.printStackTrace();
}
}
}
});
thread1.start();
}
}
No comments:
Post a Comment