ในภาษาจาวานั้นการทำงานแบบ 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>)
ซึ่งต่อไปจะเป็นตัวอย่างการใช้งานในภาษาจาวา
[sourcecode language=”java”]
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);
}
}
}
}
[/sourcecode]
จากตัวอย่างในภาษาจาวานั้น จะเห็นว่าถ้าหากต้องการให้ object ไหนทำงานแบบ multi task นั้นก็ทำให้นำ object นั้นไปเป็นค่าของ object Thread เหมือนในตัวอย่างส่วนการทำงานของ multi task นั้นก็กำหนดใน method run เหมือนเดิม จากนั้นถ้าจะให้ object ไหนเริ่มทำงานก็ทำงานการเรียกใช้ method start() ส่วนการหยุดหรือ sleep ก็เรียกใช้ method sleep เหมือนในตัวอย่าง