2012年8月24日 星期五

Thread & Runnable

Thread
public class ThreadTest{
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  CTest AAA = new CTest("AAA");
  CTest BBB = new CTest("BBB");
  AAA.start();
  BBB.start();
 }
}

public class CTest extends Thread{

 private String id;
 public CTest(String s){
  id = s;
 }

 public void run() {
 
  for(int i = 0; i < 4; i++){
   for(int j = 0; j < 10000000; j++);
    System.out.println(id + " is runing...");
  }
 }
}
=================================================
AAA is runing...
BBB is runing...
AAA is runing...
BBB is runing...
AAA is runing...
BBB is runing...
AAA is runing...
BBB is runing...
=================================================

Runnable


public class RunnableTest{
 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  CRTest AAA = new CRTest("AAA");
  CRTest BBB = new CRTest("BBB");
 
  Thread t1 = new Thread(AAA);
  Thread t2 = new Thread(BBB);
 
  t1.start();
  t2.start();
 }
}

public class CRTest implements Runnable{
 private String id;
 public CRTest(String s){
  id = s;
 }

 public void run() {
 
  for(int i = 0; i < 4; i++){
   for(int j = 0; j < 10000000; j++);
    System.out.println(id + " is runing...");
  }
 }
}
===================================
AAA is runing...
BBB is runing...
AAA is runing...
BBB is runing...
AAA is runing...
BBB is runing...
AAA is runing...
BBB is runing...
====================================

沒有留言:

張貼留言