สำหรับ Class ของ Thread จะทำการ implements ด้วย Class ของ Runnable ซึ่งนั่นหมายถึงเมื่อการสั่งให้ Thread ทำงานจะรันผ่าน Runnable
Thread Syntax (รุปแบบ 1)
public class MyClass implements Runnable {
public void run() {
}
public static void main(String[] args) throws Exception {
Thread th = new Thread(new MyClass());
th.start();
}
}
Thread Syntax (รุปแบบ 2)
public class MyClass{
public static void main(String args[]) {
startThread();
}
public static void startProgress(final String sItem) {
Runnable runnable = new Runnable() {
public void run() {
}
};
new Thread(runnable).start();
}
}
ทั้ง 2 รูปแบบสามารถใช้ได้เหมือนกัน
Example 1
MyClass.java
package com.java.myapp;
public class MyClass implements Runnable {
String sItem;
public MyClass(String strItem) {
// TODO Auto-generated constructor stub
sItem = strItem;
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Item Thread " + sItem + " (value = " + i + " )");
try {
Thread.sleep(2000);
} catch (Exception e) {
System.out.println(e);
}
}
}
public static void main(String[] args) throws Exception {
Thread t1 = new Thread(new MyClass("A"));
t1.start();
Thread t2 = new Thread(new MyClass("B"));
t2.start();
Thread t3 = new Thread(new MyClass("C"));
t3.start();
}
}
Example 2
MyClass.java
package com.java.myapp;
public class MyClass {
public static void main(String args[]) {
startProgress("A");
startProgress("B");
startProgress("C");
}
public static void startProgress(final String sItem) {
Runnable runnable = new Runnable() {
public void run() {
for (int i = 0; i <= 5; i++) {
final int value = i;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Item Thread " + sItem + " (value = " + value + " )");
}
}
};
new Thread(runnable).start();
}
}