alt/text gambar

Home

Laman

Rabu, 05 Juni 2013

Thread Utama (JAVA)


class MyThread implements Runnable
{
private Thread t;
private int n;
MyThread(String nama,int n)
{
t= new Thread(this,nama);
this.n = n;
}
public void run()
{
try
{
for (int i=0; i<n; i++)
{
System.out.println("Thread"+t.getName()+":detik ke-"+(i+1));
Thread.sleep(1000);
}
System.out.println("Thread"+t.getName()+"selesai...");
}
catch (InterruptedException ie)
{
System.out.println(ie.getMessage());
}
}
public void start()
{
t.start();
}
public Thread getThread()
{
return t;
}
}
class DemoIsAliveJoin
{
public static void main(String[]args)
throws InterruptedException
{
System.out.println("Thread utama dijalankan\n");

MyThread t1=new MyThread("pertama",2);
MyThread t2=new MyThread("kedua",3);
MyThread t3=new MyThread("ketiga",4);

t1.start();
t2.start();
t3.start();

//pada saat thread t1.t2.t3 aktif
System.out.println("t1.getThread().isAlive():" + t1.getThread().isAlive());
System.out.println("t2.getThread().isAlive():" + t2.getThread().isAlive());
System.out.println("t3.getThread().isAlive():" + t3.getThread().isAlive());
System.out.println();

//menunggu smapai thread t1,t2,t3 selesai diexekusi
t1.getThread().join();
t2.getThread().join();
t3.getThread().join();

//setelah thread t1,t2,t3 selesai
System.out.println();
System.out.println("t1.getThread().isAlive():" + t1.getThread().isAlive());
System.out.println("t2.getThread().isAlive():" + t2.getThread().isAlive());
System.out.println("t3.getThread().isAlive():" + t3.getThread().isAlive());
System.out.println("\nThread utama selesai");
}
}





Tidak ada komentar:

Posting Komentar