标签:
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次
标签:
原文地址:http://www.cnblogs.com/soaringEveryday/p/4290725.html