2013年5月16日 星期四

[JAVA} Multi Thread Console 程式

共計有三段檔案
go.java

//使用 Thread / Runnable 介面 建立執行緒
//有獨立寫出class 也有直接寫在code 裡面

public class go {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//第一種寫法 複寫 Thread 中的 run 方法
go2 another = new go2();
another.start();

//第二種寫法 複寫 Runnable 介面中的 run 方法
go3 other_inside = new go3();
Thread other = new Thread(other_inside);
other.start();

//第三種寫法 匿名類別 直接複寫 Runnable 中的 run 方法
Thread four = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<20;i++){
System.out.println(i + ". I kiss You!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
four.start();

for(int i=0;i<20;i++){
System.out.println(i + ". I hate You!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
go2.java

public class go2 extends Thread {

@Override
public void run() {
// TODO Auto-generated method stub
super.run();
for(int i=0;i<20;i++){
System.out.println(i + ". I Love You");
try{
Thread.sleep(2000);
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
}
go3.java

public class go3 implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
System.out.println(i + ". I like You!!");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...