性格决定命运,气度影响格局
posts - 20, comments - 18, trackbacks - 0, articles - 1
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

线程的创建与启动

Posted on 2007-08-01 18:46 尚爱军 阅读(144) 评论(0)  编辑  收藏

方法一:   
             1.定义线程类实现Runnable接口
             2.Thread myThread = new Thread(target) //target 为Runnable接口类型。
             3.Runnable中只有一个方法:public void run(); //用以定义线程云形体。
             4.使用Runnable接口可以为多个线程提供共享的数据。
             5.在实现Runnable接口的类的run方法定义中可以使用Thread静态方法:
                                             public static Thread currentThread()//获取当前线程的引用。

举例:
         public class TestThread1()  {
            public static void main(String[] args) {
               Runner1 r= new Runner1();
               Thread t = new Thread(r);
               t.start();

               for(int i=0; i<100; i++) {
                  System.out.println("Main Thread:------" + i);
               }
            }
         }
       
         class Runner1 implements Runnable {
            public void run() {
               for (int i=0; i<100; i++) {
                  System.out.println("Runner1 :" + i);
               }
            }
         }

方法二:
             1.可以定义一个Thread的子类并重写其run方法,如:
                             class MyThread extends Thread {
                                    public void run() {......}
                             }
             2.然后生成该类的对象:
                             MyThread myThread = new MyThread(......)

举例:
         public class TestThread (
            public static void main(String[] args) {
               Runner1 r = new Runner1();
               r.start();

               for(int i=0; i<100; i++) {
               System.out.println("Main Thread:------" + i);
               }
             }
         )
         

         class Runner1 extends Thread {
            public void run() {
               for (int i=0; i<100; i++) {
               System.out.println("Runner1 :" + i);
            }
         }   

结论:使用第一种方法生成多线程好,因为一个类可以继承多个接口。而类继承只能是单继承。

只有注册用户登录后才能发表评论。


网站导航: