Java实现多线程的两种方法

Thread类

 1 package com.hu.thread;
 2 
 3 public class MyThread extends Thread{
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         MyThread mt1=new MyThread();
11         MyThread mt2=new MyThread();
12         mt1.start();
13         mt2.start();
14     }
15 
16     @Override
17     public void run() {
18         // TODO Auto-generated method stub
19         super.run();
20         for(int i=0;i<100;i++){
21             System.out.println(Thread.currentThread().getName()+" "+i);
22             try {
23                 Thread.sleep(10);
24             } catch (InterruptedException e) {
25                 // TODO Auto-generated catch block
26                 e.printStackTrace();
27             }
28         }
29     }
30 }

Runnable接口

 1 package com.hu.runnable;
 2 
 3 public class MyRun implements Runnable{
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         new Thread(new MyRun()).start();
11         new Thread(new MyRun()).start();
12     }
13 
14     @Override
15     public void run() {
16         // TODO Auto-generated method stub
17         for(int i=0;i<100;i++){
18             System.out.println(Thread.currentThread().getName()+" "+i);
19             try {
20                 Thread.sleep(10);
21             } catch (InterruptedException e) {
22                 // TODO Auto-generated catch block
23                 e.printStackTrace();
24             }
25         }
26     }
27 }

 

posted @ 2012-06-11 13:10  丛林听雨  阅读(164)  评论(0编辑  收藏  举报