qiezijiajia

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

概要


1.Thread与Runnable的简单介绍

2.Thread与Runnable的区别

3.Thread与Runnable举例

 

Thread与Runnable的简介

Runnable就是一个接口,实现接口就需要实现run方法;

public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

Thread其实也是实现了Runnable接口,如源码所示,在继承Thread时,需要重写run方法。

public
class Thread implements Runnable {
public void run() {  //实现的是Runnable接口
        if (target != null) {
            target.run();  //此处的target是Runnable类型
        }
    }

 

Thread与Runnable的区别

1.二者都是多线程的实现方式;

2.Thread是类,Runnable是接口,一个类可以实现多个接口,所以Runnable具有更好的扩展性。

3.Runnable能够实现对象的共享,比如说基于某一个Runnable对象,多个线程可以同时共享Runnable对象上的资源。后面代码后说明。

 

Thread与Runnable举例

1.Thread,比如实现一个ThreadTest

public class ThreadTest extends Thread{

    private int ticket=5;
    public void run(){

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

            if(this.ticket>0){

                System.out.println(this.currentThread().getName()+" sell "+this.ticket--);
            }
        }
    }

    public static void main(String[] args){

        ThreadTest test1=new ThreadTest();
        ThreadTest test2=new ThreadTest();
        ThreadTest test3=new ThreadTest();
        test1.start();
        test2.start();
        test3.start();
    }

这样的输出结果分别为三个线程分别卖出5张票:创建了三个ThreadTest的实例,每个实例调用start来启动线程来调用run方法。

Thread-0 sell 5
Thread-2 sell 5
Thread-1 sell 5
Thread-2 sell 4
Thread-0 sell 4
Thread-2 sell 3
Thread-1 sell 4
Thread-2 sell 2
Thread-2 sell 1
Thread-0 sell 3
Thread-0 sell 2
Thread-0 sell 1
Thread-1 sell 3
Thread-1 sell 2
Thread-1 sell 1

 

2.Runnable的示例

public class RunnableTest implements Runnable {
    private int ticket=5;
    @Override
    public void run() {

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

            if(this.ticket>0){

                System.out.println(Thread.currentThread().getName()+" sell "+this.ticket--);
            }
        }
    }

    public static void main(String[] args){

        RunnableTest runnableTest=new RunnableTest();
        Thread test1=new Thread(runnableTest);
        Thread test2=new Thread(runnableTest);
        Thread test3=new Thread(runnableTest);
        test1.start();
        test2.start();
        test3.start();

    }
}

创建三个Thread实例,但是用的一个Runnable对象,所有输出结果为三个线程卖5张票:

Thread-0 sell 4
Thread-0 sell 2
Thread-0 sell 1
Thread-2 sell 3
Thread-1 sell 5

 

posted on 2017-09-07 11:06  qiezijiajia  阅读(151)  评论(0编辑  收藏  举报