ข้ามไปเนื้อหา

ผู้ใช้:Thaicoding

จากวิกิพีเดีย สารานุกรมเสรี

ภาษาจาวา Implementing Runnable Interface ในภาษาจาวานั้นการทำงานแบบ multi task หรือการทำงานหลายงานพร้อมกันนั้นนอกจากการ extends Threads แล้วยังมีอีกวิธีหนึ่งก็คือ การ implementing Interface Runnable ซึ่งก็จะมีลักษณะคล้ายๆกันซึ่งจะสะดวกตรงที่ว่าเราจะสั่งให้ object ไหนทำงานแบบ multi task ได้ซึ่งรูปแบบการใช้งานนั้นก็ต้องทำการ implement class Runnable และมีการกำหนดค่าให้ object ไหนว่าจะทำงานแบบ multi task บ้างซึ่งต้องกำหนดตอนสร้าง object ตอนเรียกใช้ constructors ซึ่งในภาษาจาวามีรูปแบบดังนี้

Thread (Runnable <object>) Thread(Runnable <object>, String <name>) ซึ่งต่อไปจะเป็นตัวอย่างการใช้งานในภาษาจาวา

public class RunnableShowName implements Runnable { public static void main(String[] args) { Thread thread1 = new Thread(new RunnableShowName()); Thread thread2 = new Thread(new RunnableShowName());

thread1.start(); thread2.start(); } public void run() { int pause; for(int i=0; i<10; i++) { try { //Use static method currentThread to get //reference to current thread and then call // method getName on that reference... System.out.println(Thread.currentThread().getName()+ "being executed."); pause = (int)(Math.random()*3000); //Call static method sleep// Thread.sleep(pause); } catch (InterruptedException interruptEx) { System.out.println(interruptEx); } } } }

ไฟล์:Http://www.thaicoding.net/wp-content/uploads/2010/01/runnable.jpg จากตัวอย่างในภาษาจาวานั้น จะเห็นว่าถ้าหากต้องการให้ object ไหนทำงานแบบ multi task นั้นก็ทำให้นำ object นั้นไปเป็นค่าของ object Thread เหมือนในตัวอย่างส่วนการทำงานของ multi task นั้นก็กำหนดใน method run เหมือนเดิม จากนั้นถ้าจะให้ object ไหนเริ่มทำงานก็ทำงานการเรียกใช้ method start() ส่วนการหยุดหรือ sleep ก็เรียกใช้ method sleep เหมือนในตัวอย่าง