Home > Java > Thread dalam Java Part 2

Thread dalam Java Part 2

February 21, 2011 Leave a comment Go to comments

Seperti dalam post Thread dalama Java Part 1, dalam membuat Thread ada dua cara yaitu dengan implements interface Runnable atau dengan extends class Thread.

Berikut ini sedikit contoh dalam membuat Thread dalam Java

  1. Implement Interface Runnable

nama file ThreadJavaSatu.java

package threadjavasatu;

/**
*
* @author Taeyeon
*/
public class ThreadRunnable implements Runnable {
Thread runner;
public ThreadRunnable()
{

}

public ThreadRunnable(String threadName)
{
runner = new Thread(this, threadName);
System.out.println(runner.getName());
runner.start();
}
public void run() {
System.out.println(Thread.currentThread());
}

}

nama file main.java

package threadjavasatu;

/**
*
* @author Taeyeon
*/
public class ThreadRunnable implements Runnable {
Thread runner;
public ThreadRunnable()
{

}

public ThreadRunnable(String threadName)
{
runner = new Thread(this, threadName);
System.out.println(runner.getName());
runner.start();
}
public void run() {
System.out.println(Thread.currentThread());
}

}
Download File
2. Extends Class Thread

nama file ExThread.java

package threadjavadua;

/**
*
* @author Taeyeon
*/
public class ExThread extends Thread {

public ExThread()
{

}
public ExThread(String threadName)
{
super(threadName);
System.out.println(this);
}

public void run()
{
System.out.println(Thread.currentThread().getName());
}

}

nama file main.java

package threadjavadua;

/**
*
* @author Taeyeon
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Thread threadSatu = new Thread(new ExThread(),”ThreadSatu”);
Thread threadDua = new Thread(new ExThread(),”ThreadDua”);
Thread threadTiga = new Thread();
Thread threadEmpat = new Thread();
Thread threadLima = new ExThread(“thread5”);
threadSatu.start();
threadDua.start();
threadTiga.start();
threadEmpat.start();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
}

System.out.println(Thread.currentThread());

}

}
Download File
Semoga bermanfaat😀

Salah koreksi saya

Referensi : Dari berbagai sumber

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: