码迷,mamicode.com
首页 > 其他好文 > 详细

Thread和Runnable的区别

时间:2015-02-13 18:26:49      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

1.  首先是使用上的区别,先看代码:

class MyThread extends Thread
{
    @Override
    public void run() {
        System.out.println("do things");
    }
}

class MyRunnable implements Runnable
{

    @Override
    public void run() {
        System.out.println("do things");
        
    }
}

可以看到使用Thread是继承关系,而使用Runnable是实现关系。我们知道java不支持多继承,如果要实现多继承就得要用implements,所以使用上Runnable更加的灵活

 

2. 关于共享数据的问题

Runnable是可以共享数据的,多个Thread可以同时加载一个Runnable,当各自Thread获得CPU时间片的时候开始运行runnable,runnable里面的资源是被共享的

这里用实例来讲解:

首先分别定义一个thread和一个runnable,things这个变量即为所想要共享的资源

class MyThread extends Thread
{
    int things = 5;
    @Override
    public void run() {
        while(things > 0)
        {
            System.out.println(currentThread().getName() + " things:" + things);
            things--;
        }
    }
}

class MyRunnable implements Runnable
{
    String name;
    
    public MyRunnable(String name)
    {
        this.name = name;
    }
    
    int things = 5;
    @Override
    public void run() {
        while(things > 0)
        {
       things--;
System.out.println(name
+ " things:" + things); } } }

随后,用三个Thread来运行看:

public class ThreadTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        MyThread thread1 = new MyThread();
        MyThread thread2 = new MyThread();
        MyThread thread3 = new MyThread();
        thread1.start();
        thread2.start();
        thread3.start();
        
    }

}

结果如下:

Thread-0 things:5
Thread-0 things:4
Thread-2 things:5
Thread-1 things:5
Thread-1 things:4
Thread-1 things:3
Thread-1 things:2
Thread-1 things:1
Thread-2 things:4
Thread-2 things:3
Thread-2 things:2
Thread-2 things:1
Thread-0 things:3
Thread-0 things:2
Thread-0 things:1

可以看到每个Thread都是5个things,所以资源是不共享的

下面用一个Runnable在3个Thread中加载尝试看看:

 

public class ThreadTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        MyRunnable run = new MyRunnable("run");
        Thread th1 = new Thread(run, "Thread 1");
        Thread th2 = new Thread(run, "Thread 2");
        Thread th3 = new Thread(run, "Thread 3");

        th1.start();
        th2.start();
        th3.start();
        
    }

}

结果如下:

run things:3
run things:2
run things:1
run things:0
run things:3

一共打印出了5次,表示things资源使用了5次

 

Thread和Runnable的区别

标签:

原文地址:http://www.cnblogs.com/soaringEveryday/p/4290725.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!