CONTOH THREAD
CONTOH 1
public class latihan_thread {
public static void main(String[] args) {
int jumlah = 10;
Thread thread = new Thread(){
public void run(){
try{
for(int w=1; w<=jumlah; w++){
System.out.println("Nomor: "+w);
sleep(1000); //Waktu Pending
}
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
};
thread.start();
}
}
CONTOH KE 2 PROGRAM THREAD
import static java.lang.Thread.sleep;
public class latihan_thread{
Thread thread;
int jumlah = 7;
public static void main(String[] args) {
latihan_thread test = new latihan_thread();
test.proses_satu();
test.proses_dua();
}
void proses_satu(){
thread = new Thread(){
public void run(){
try{
for(int w=1; w<=jumlah; w++){
System.out.println("Nomor: "+w);
sleep(1000); //Waktu Pending
}
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
};
thread.start();
}
void proses_dua(){
thread = new Thread(){
public void run(){
try{
for(int w=1; w<=jumlah; w++){
System.out.println("Salam Programmer");
sleep(1000); //Waktu Pending
}
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
};
thread.start();
}
}
Contoh thread 3
public class Ujithread {
public static void main(String[] args) {
Mobil m1 = new Mobil("M-1");
Mobil m2 = new Mobil("M-2");
m1.start();
m2.start()
}
}
class Mobil extends Thread{
//konstruktor
public Mobil(String id){
super(id);
}
public void run() {
String nama = getName();
for (int i=0; i<5; i++) {
try{
sleep(1000); //tunggu 1 detik
}
catch(InterruptedException ie){
System.out.println("terinterupsi");
}
System.out.println("Thread " + nama + " :Posisi " + i);
}
}
}
CONTOH KE 4
public class Ujithread2 {
public static void main(String[] args) {
Thread m1 = new Thread(new Mobil("M-1"));
Thread m2 = new Thread(new Mobil("M-2"));
m1.start();
m2.start();
}
}
class Mobil implements Runnable{
String nama;
//konstruktor
public Mobil(String id) {
nama=id;
}
public void run() {
for(int i=0; i<5; i++) {
try{
Thread.currentThread().sleep(1000);
}
catch(InterruptedException ie){
System.out.println("terinterupsi");
}
System.out.println("Thread " + nama + " :Posisi " + i);
}
}
}