Thread bagian 2

2. Extending Kelas Thread

Prosedur untuk menciptakan threads berdasarkan mengextend Thread adalah sbb:

  1. 1. Sebuah kelas mengekstend kelas Thread selanjutnya mengoverride method run() dari kelas Thread untuk menentukan kode yang dieksekusikan oleh thread.
  2. 2. Subclass ini boleh memanggil sebuah konsrtruktor Thread secear eksplisit di konstruktornya sendiri untuk menginisialisasi thread tersebut, menggunakan pemanggilan super().
  3. 3. Method start() yang diwariskan dari kelas Thread djalankan pada objek dari kelas untuk membuat thread memenuhi syarat dijalankan.

Dibawah ini adalah sebuah program yang mengilustrasikan dan menjalankan threads dengan mengextend kelas Thread yang merupakan cara lain dari pengimplementasian interface Runnable.

class XThread extends Thread {

XThread() {
}
XThread(String threadName) {
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}

public class ThreadExample {

public static void main(String[] args) {
Thread thread1 = new Thread(new XThread(), “thread1”);
Thread thread2 = new Thread(new XThread(), “thread2”);
//The below 2 threads are assigned default names
Thread thread3 = new XThread();
Thread thread4 = new XThread();
Thread thread5 = new XThread(“thread5”);
//Start the threads
thread1.start();
thread2.start();
thread3.start();
thread4.start();
try {
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e) {
}
//Display info about the main thread
System.out.println(Thread.currentThread());
}
}

Output

Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]