Thread เป็นฟังก์ชันที่ทำงานพร้อมกับส่วนอื่นของโปรแกรม ทุกโปรแกรม Java มีอย่างน้อย 1 เธรด คือ main thread สร้างโดย JVM ตอนเริ่มโปรแกรมเมื่อเรียก main() ใน Java สร้างเธรดได้ 2 วิธี: extends Thread class หรือ implements Runnable interface เราสามารถสร้างเธรดด้วย anonymous class โดยไม่ extends Thread class ได้ในโปรแกรมด้านล่าง
ตัวอย่าง
public class AnonymousThreadTest {
public static void main(String[] args) {
new Thread() {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("run() method: " + i);
}
}
}.start();
for (int j = 1; j <= 5; j++) {
System.out.println("main() method: " + j);
}
}
}
ผลลัพธ์
main() method: 1 run() method: 1 main() method: 2 run() method: 2 main() method: 3 run() method: 3 main() method: 4 run() method: 4 main() method: 5 run() method: 5