Implement the run ()
method by inheriting the Thread class.
public class Qiita {
public static void main(String[] args) {
new HelloThread("World!").start();
new HelloThread("Qiita!").start();
}
}
class HelloThread extends Thread {
private String message;
public HelloThread(String message) {
this.message = message;
}
public void run() {
System.out.print("Hello, " + message);
}
}
Pass the class that implements the Runnable interface to the Thread constructor.
public class Qiita {
public static void main(String[] args) {
new Thread(new Greeting("World!")).start();
new Thread(new Greeting("Qiita!")).start();
}
}
class Greeting implements Runnable {
private String message;
public Greeting(String message) {
this.message = message;
}
public void run() {
System.out.print("Hello, " + message);
}
}
Abstract thread creation with ThreadFactory.
public class Qiita {
public static void main(String[] args) {
ThreadFactory factory = Executors.defaultThreadFactory();
factory.newThread(new Greeting("Qiita!")).start();
}
}
Recommended Posts