Java 多线程之 Runnable VS Thread 及其资源共享问题

对于 Java 多线程编程中的 implements Runnable 与 extends Thread,部分同窗可能会比较疑惑,它们之间究竟有啥区别和联系呢?他们是否是没啥区别随便选呢?实际中究竟该选择哪个呢?html

甚至网上很多博客文章以讹传讹得出很多谬论,那今天的走进科学栏目将带您一一揭开谜底。java

一、区别:

其实这块主要是围绕着接口和抽象类的区别以及一些设计原则而言的。面试

1.1 Inheritance Option:   

The limitation with "extends Thread" approach is that if you extend Thread,  you can not extend anything else . Java does not support multiple inheritance.  In reality , you do not need Thread class behavior , because in order to use a thread you need to instantiate one anyway. On the other hand, Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior that will be run by separate thread.编程

1.2 Reusability

In "implements Runnable" , we are creating a different Runnable class for a specific behavior  job (if the work you want to be done is job). It gives us the freedom to reuse the specific behavior job whenever required. "extends Thread"  contains both thread and job specific behavior code. Hence once thread completes execution , it can not be restart again.   安全

1.3 Object Oriented Design:  

Implementing Runnable should be preferred . It does not specializing or modifying the thread behavior . You are giving thread something to run. We conclude that Composition is the better way. Composition means two objects A and B satisfies has-a  relationship. "extends Thread"  is not a good Object Oriented practice.多线程

1.4 Loosely-coupled

"implements Runnable" makes the code loosely-coupled and easier to read . Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code. "extends Thread"  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.并发

1.5 Functions overhead :  

"extends Thread"  means inheriting all the functions of the Thread class which we may do not need .  job can be done easily by Runnable without the Thread class functions overhead.app

至此,我的是推荐优先选择  implements Runnable 。dom

二、联系:

2.1 其实Thread类也是Runnable接口的子类

public class Thread extends Object implements Runnable

2.2 启动线程都是 start() 方法

追踪Thread中的start()方法的定义,能够发现此方法中使用了private native void start0();其中native关键字表示能够调用操做系统的底层函数,这样的技术称为JNI技术(java Native Interface)。函数

可是在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。此时观察Thread类,有一个构造方法:public Thread(Runnable targer),此构造方法接受Runnable的子类实例,也就是说能够经过Thread类来启动Runnable实现的多线程。

可是能够看到它们子线程运行的位置不一样,Thread运行在父类的run方法中,Runnable运行在实现Runnable接口的子类对象run方法中。

2.3 网传的一种缪论:用Runnable就能够实现资源共享,而 Thread 不能够

有同窗的例子是这样的,参考:http://developer.51cto.com/art/201203/321042.htm

package tmp;

class MyThread extends Thread {

	private int ticket = 10;
	private String name;

	public MyThread(String name) {
		this.name = name;
	}

	public void run() {
		for (int i = 0; i < 500; i++) {
			if (this.ticket > 0) {
				System.out.println(this.name + "卖票---->" + (this.ticket--));
			}
		}
	}
}

public class ThreadDemo {

	public static void main(String[] args) {
		MyThread mt1 = new MyThread("一号窗口");
		MyThread mt2 = new MyThread("二号窗口");
		MyThread mt3 = new MyThread("三号窗口");
		mt1.start();
		mt2.start();
		mt3.start();
	}

}

// 一号窗口卖票---->10
// 二号窗口卖票---->10
// 二号窗口卖票---->9
// 二号窗口卖票---->8
// 三号窗口卖票---->10
// 三号窗口卖票---->9
// 三号窗口卖票---->8
...

Runnable 代码:

package tmp;

class MyThread1 implements Runnable {
	private int ticket = 10;
	private String name;

	public void run() {
		for (int i = 0; i < 500; i++) {
			if (this.ticket > 0) {
				System.out.println(Thread.currentThread().getName() + "卖票---->" + (this.ticket--));
			}
		}
	}
}

public class RunnableDemo {

	public static void main(String[] args) {
		MyThread1 mt = new MyThread1();
		Thread t1 = new Thread(mt, "一号窗口");
		Thread t2 = new Thread(mt, "二号窗口");
		Thread t3 = new Thread(mt, "三号窗口");
		t1.start();
		t2.start();
		t3.start();
	}

}

// 二号窗口卖票---->10
// 三号窗口卖票---->9
// 三号窗口卖票---->7
// 一号窗口卖票---->9
// 三号窗口卖票---->6
// 二号窗口卖票---->8
// 三号窗口卖票---->4
// 一号窗口卖票---->5
// 三号窗口卖票---->2
// 二号窗口卖票---->3
// 一号窗口卖票---->1

由此差异,有同窗就得出了一个结论:用Runnable就能够实现资源共享,而 Thread 不能够,这是他们的主要差异之一。。。

其实仔细看看代码就知道,这只是两种写法的区别,根本就不是 implements Runnable 与 extends Thread 的区别:

MyThread1 mt = new MyThread1();  
Thread t1 = new Thread(mt,"一号窗口");  
Thread t2 = new Thread(mt,"二号窗口");  
Thread t3 = new Thread(mt,"三号窗口"); 
////////////////
Thread t1 = new Thread(new MyThread1(),"一号窗口");  
Thread t2 = new Thread(new MyThread1(),"二号窗口");  
Thread t3 = new Thread(new MyThread1(),"三号窗口");

其实,想要“资源共享”,Thread 也能够作到的:

private static int ticket = 10;

// 三号窗口卖票---->10
// 一号窗口卖票---->9
// 二号窗口卖票---->9
// 一号窗口卖票---->7
// 一号窗口卖票---->5
// 三号窗口卖票---->8
// 一号窗口卖票---->4
// 二号窗口卖票---->6
// 一号窗口卖票---->2
// 三号窗口卖票---->3
// 二号窗口卖票---->1

经过 static 就能够实现拥有共同的ticket=10,但问题也来了,你会发现一二号窗口都卖了第 9 张票。

三、资源共享带来的问题:多线程的线程安全问题

上面的例子以及结果证实了多线程场景下,须要留意线程安全的问题:

3.1 同步run()方法

public synchronized void run()

3.2 同步 class 对象

synchronized (Test.class)

3.3 同步某些静态对象

private static final Object countLock = new Object();
synchronized (countLock) {
    count++;
}

3.4 最后给个完整的例子,模拟在线售票与查询:

package tmp;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

public class Demo implements Runnable {
	String name;
	//	static Integer tickets = 20;
	private static AtomicInteger tickets = new AtomicInteger(20);

	public Demo(String name) {
		this.name = name;
	}

	public void run() {
		for (int i = 1; i <= 20; i++) {
			synchronized (tickets) {
				if (tickets.get() > 0) {
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
					System.out.println("我取票第" + ": " + tickets.getAndDecrement() + " 张票。");
					//					tickets--;
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
					}
					System.out.println("==========如今查询还剩" + ": " + tickets.get() + " 张票。");
				}
			}
		}
	}

	public static void main(String[] args) throws IOException {
		Demo demo = new Demo("hello");
		new Thread(demo).start();
		new Thread(demo).start();
		new Thread(demo).start();
	}
}

到这儿,本期走进科学也要跟你们说声再见了,其实聊着聊着感受都快跑题了,多线程这块话题不少,很复杂,须要慢慢实践与积累,祝你们玩的愉快。

四、一道多线程题目使用 java.util.concurrent 包的解决方案

package thread;
/**
题目:

要求用三个线程,按顺序打印1,2,3,4,5.... 71,72,73,74, 75.
线程1先打印1,2,3,4,5, 而后是线程2打印6,7,8,9,10, 
而后是线程3打印11,12,13,14,15. 
接着再由线程1打印16,17,18,19,20....以此类推, 直到线程3打印到75。

分析:感受出题人是要考察一下你是否可以很好的控制多线程,让他们有序的进行。
一、线程池:3个线程,须要使用并发库的线程池
二、锁(lcok):在打印的时候,只容许一个线程进入,其余的线程等待

 * Date:     2013-6-23 上午3:28:56 <br/>
 * @author   http://hi.baidu.com/leejun_2005/item/1a7bb2085db78a1deafe38ba
 */
import java.util.HashMap;  
import java.util.Map;  
import java.util.concurrent.CountDownLatch;  
import java.util.concurrent.ExecutorService;  
import java.util.concurrent.Executors;  
import java.util.concurrent.locks.Condition;  
import java.util.concurrent.locks.Lock;  
import java.util.concurrent.locks.ReentrantLock;  
 
public class NumberPrinter {  
 
    private Lock lock = new ReentrantLock();  
 
    private Condition c1 = lock.newCondition();  
    private Condition c2 = lock.newCondition();  
    private Condition c3 = lock.newCondition();  
 
    private Map<Integer, Condition> condtionContext =   
        new HashMap<Integer, Condition>();  
 
    public NumberPrinter() {  
        condtionContext.put(Integer.valueOf(0), c1);  
        condtionContext.put(Integer.valueOf(1), c2);  
        condtionContext.put(Integer.valueOf(2), c3);  
    }  
      
    private int count = 0;     
      
    public void print(int id) {  
        lock.lock();  
        try {  
            while(count*5 < 75) {  
                int curID = calcID();  
                if (id == curID) {  
                    for (int i = 1; i<=5; i++) {  
                        System.out.println(Thread.currentThread().getName() + " -- " + (count*5 +i) + ",");  
                    }  
                    System.out.println();  
                    count++;  
                    int nextID = calcID();  
                    Condition nextCondition = condtionContext.get(  
                            Integer.valueOf(nextID));  
                    //通知下一线程  
                    nextCondition.signal();  
                } else {  
                    Condition condition = condtionContext.get(  
                            Integer.valueOf(id));  
                    condition.await();  
                }  
            }  
            //通知线程结束  
            for(Condition c : condtionContext.values()) {  
                c.signal();  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            lock.unlock();  
        }  
    }  
      
    private int calcID() {  
        // TODO Auto-generated method stub  
        return count % 3;  
    }  
 
 
    /**  
     * @param args  
     */ 
    public static void main(String[] args) {  
        ExecutorService executor = Executors.newFixedThreadPool(3);  
        final CountDownLatch latch = new CountDownLatch(1);     
        final NumberPrinter printer = new NumberPrinter();   
        for (int i = 0; i < 3; i++) {     
            final int id = i;  
            executor.submit(new Runnable() {  
                public void run() {  
                    // TODO Auto-generated method stub  
                    try {  
                        latch.await();  
                    } catch (InterruptedException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    printer.print(id);  
                }  
            });  
        }  
        System.out.println("三个任务开始顺序打印数字。。。。。。");   
        latch.countDown();  
        executor.shutdown();  
    }  
}
三个任务开始顺序打印数字。。。。。。
pool-1-thread-1 -- 1,
pool-1-thread-1 -- 2,
pool-1-thread-1 -- 3,
pool-1-thread-1 -- 4,
pool-1-thread-1 -- 5,

pool-1-thread-2 -- 6,
pool-1-thread-2 -- 7,
pool-1-thread-2 -- 8,
pool-1-thread-2 -- 9,
pool-1-thread-2 -- 10,

pool-1-thread-3 -- 11,
pool-1-thread-3 -- 12,
pool-1-thread-3 -- 13,
pool-1-thread-3 -- 14,
pool-1-thread-3 -- 15,

pool-1-thread-1 -- 16,
pool-1-thread-1 -- 17,
pool-1-thread-1 -- 18,
pool-1-thread-1 -- 19,
pool-1-thread-1 -- 20,

pool-1-thread-2 -- 21,
pool-1-thread-2 -- 22,
pool-1-thread-2 -- 23,
pool-1-thread-2 -- 24,
pool-1-thread-2 -- 25,

pool-1-thread-3 -- 26,
pool-1-thread-3 -- 27,
pool-1-thread-3 -- 28,
pool-1-thread-3 -- 29,
pool-1-thread-3 -- 30,

...

五、附:白话并发

办公室只有一个卫生间,一次只能容纳一我的方便,这个卫生间就是竞争条件(Race Condition)。当一我的进去后就在门口牌子上标识为“有人”,这个就至关因而线程的加锁,告诉其它同时间想要上厕所的人,这个资源已被我占位,其余人就须要等待,这叫wait。只有当前面的人出来后,并把牌子置为“无人”时,其它人才有机会使用。当只有一个蹲位时,一次只能进一我的,翻动一块牌子加一把锁,这个就叫互斥锁(Mutex)。若是卫生间里有多个蹲位,再简单地用一块牌子来标识就不行了,须要作一个电子公告牌,进去一我的电子公告牌就把可用数量减1,出来一我的数量加1,数量不为0时,有人来直接进去就好了不用等待,这个叫信号量(Semaphores)。若是出来的人是随机通知等待的某一我的,这叫notify,若是他是对着全部等待的人喊一嗓子,就是notifyAll。若是使用notify,有些倒霉的家伙可能永远也不会被通知到,这太不人性了,而若是使用nofityAll就意味着全部等待的人须要竞争资源,仍是会在倒霉蛋永远轮不到。解决的办法一是按时间顺序先到先得,顺序进入,火车站的厕所常常会看到这种状况,老是有机会轮到本身,这叫公平锁(FairLock)。还有一种状况,就是大老板也在排队,通常状况下大老板时间宝贵,能够优先考虑让他先上,这叫线程优先级,一共有10个级别。优先级只能保证级别高的优先被调度到,但不能保证必定会被调度到。

两个好基友一块儿在蹲坑,只有一卷手纸,一我的去取时另外一个就不能同时去取,这叫基于共享内存的线程间通讯。两我的都是烟鬼,但只带了一个打火机,一我的用完以后递给另一我的,

进程和线程的区别:一个办公区有多个卫生间,每一个卫生间的资源是独立的,不会相互依赖,至关因而进程。每一个卫生间有多个蹲位,每一个蹲位至关因而一个线程,蹲位越多并发处理能力越强。但多个同一个卫生间的多个蹲位共用一个洗手台,若是蹲位过多,洗手台的资源会成为瓶颈。

Refer:

[1] Java线程面试题 Top 50

http://www.importnew.com/12773.html

相关文章
相关标签/搜索