Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

จะสร้างเธรดโดยไม่ต้องใช้อินเทอร์เฟซ Runnable ใน Java ได้อย่างไร


เธรดสามารถเรียกได้ว่าเป็น น้ำหนักเบา กระบวนการ. Java รองรับ มัลติเธรด ดังนั้นจึงทำให้แอปพลิเคชันของเราสามารถดำเนินการ สองงานขึ้นไปพร้อมกัน . โปรแกรม Java ทั้งหมดมีอย่างน้อยหนึ่งเธรด เรียกว่า เธรดหลัก ซึ่งสร้างโดย Java Virtual Machine (JVM) ที่โปรแกรมเริ่มต้นเมื่อ main() เมธอดถูกเรียกใช้ด้วยเธรดหลัก มีสองวิธีในการสร้างเธรดใน Java โดย ขยายคลาสเธรด หรือโดยใช้งานอินเทอร์เฟซ Runnable

นอกจากนี้เรายังสามารถสร้างเธรด โดยไม่ต้อง กำลังดำเนินการ รันได้ อินเทอร์เฟซ ในโปรแกรมด้านล่าง

ตัวอย่าง

public class CreateThreadWithoutImplementRunnable { //
without implements Runnable
   public static void main(String[] args) {
      new Thread(new Runnable() {
         public void run() {
            for (int i=0; i <= 5; i++) {
               System.out.println("run() method of Runnable interface: "+ i);
            }
         }
      }).start();
      for (int j=0; j <= 5; j++) {
         System.out.println("main() method: "+ j);
      }
   }
}

ผลลัพธ์

main() method: 0
run() method of Runnable interface: 0
main() method: 1
run() method of Runnable interface: 1
main() method: 2
run() method of Runnable interface: 2
main() method: 3
run() method of Runnable interface: 3
main() method: 4
run() method of Runnable interface: 4
main() method: 5
run() method of Runnable interface: 5