`
H小阿飞
  • 浏览: 274431 次
  • 性别: Icon_minigender_1
  • 来自: 南通
社区版块
存档分类
最新评论

线程的实现

 
阅读更多

  1. 继承 Thread  

 

package main.thread;

public class Machine extends Thread{

    public void run(){

       for(int a=0; a<10; a++){

           System.out.println(currentThread().getName()+":"+a);

           try{

              sleep(100);      //给其他线程运行的机会,这样machine1与machine2线程属于分时调度模式

           }catch(InterruptedException e){

              throw new RuntimeException(e);

           }

       }

    }

    public static void main(String[] args){

       System.out.println(currentThread().getName());  //该主线程

       Machine machine1 = new Machine();

       Machine machine2 = new Machine();     

       machine1.start();    //启动第一个Machine线程

       machine2.start();     //启动第二个Machine线程

    }

}
 

 

  2. 实现 Runable 接口

    Java 不允许一个类继承多个类,因此一旦一个类继承了 Thread 类,就不能再继承其他的类。为了解决这一问题, Java 提供了 java.lang.Runnale 接口,它有一个 run() 方法 ,定义如下:

   public void run();  

 

package main.thread;

public class Machine implements Runnable{

    @Override

    public void run() {

       // TODO Auto-generated method stub

       for(int a=0; a<10; a++){

       System.out.println(Thread.currentThread().getName()+":"+a);

       try{

           Thread.sleep(100);

       }catch(InterruptedException e){

           throw new RuntimeException(e);

       }

      }

    }

    public static void main(String[] args){

       Machine machine = new Machine();

       Thread t1 = new Thread(machine);

       Thread t2 = new Thread(machine);

       t1.start();

       t2.start();

    }

}

  

 

注: Thread 类中定义了如下形式的构造方法:

Thread(Runnable runnable)    // 当线程启动时,讲执行参数 runnable 所引用对象的 run() 方法

 

1
3
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics