Java 多线程(1)-Thread和Runnable

Java多线程之Thread与Runnable对比
本文探讨了Java中实现多线程的两种主要方式:通过继承Thread类和实现Runnable接口。这两种方法各有优劣,继承Thread类限制了进一步的继承能力,但每个线程都有独立的状态;实现Runnable接口则允许类继承其他类,并且多个线程可以共享同一对象状态。文章通过示例代码展示了它们的区别,并建议通常情况下优先使用Runnable接口。

一提到Java多线程,首先想到的是Thread继承和Runnable的接口实现

Thread继承

public class MyThread extends Thread {
	public void run(){
		int i = 0;
		System.out.println("--------------"+i++);
	}
}

 Runnable接口实现

public class RunnableImpl implements Runnable {
	private long value = 0;
	@Override
	public synchronized void run() {
		while(ThreadMain.tickets > 0){
			System.out.println(Thread.currentThread().getName()+ "------------"+ --ThreadMain.tickets);
		}
	}
}

 两者都可以实现多线程程序的创建。实际上,我们查看Thread的代码实现,也可以发现,Thread实际上也是实现了Runnable接口。

public
class Thread implements Runnable {
    /* Make sure registerNatives is the first thing <clinit> does. */
    private static native void registerNatives();
    static {
        registerNatives();
    }

    private char        name[];
    private int         priority;
    private Thread      threadQ;
    private long        eetop;
......
}

 那么Thread 和Runnabe 有什么区别呢?

The most common difference is

  • When you extends Thread class, after that you can’t extend any other class which you required. (As you know, Java does not allow inheriting more than one class).
  • When you implements Runnable, you can save a space for your class to extend any other class in future or now.

However, the significant difference is.

  • When you extends Thread class, each of your thread creates unique object and associate with it.
  • When you implements Runnable, it shares the same object to multiple threads.

Thread vs Runnable

class ImplementsRunnable implements Runnable {

	private int counter = 0;

	public void run() {
		counter++;
		System.out.println("ImplementsRunnable : Counter : " + counter);
	}
}

class ExtendsThread extends Thread {

	private int counter = 0;

	public void run() {
		counter++;
		System.out.println("ExtendsThread : Counter : " + counter);
	}
}

public class ThreadVsRunnable {

	public static void main(String args[]) throws Exception {
		// Multiple threads share the same object.
		ImplementsRunnable rc = new ImplementsRunnable();
		Thread t1 = new Thread(rc);
		t1.start();
		Thread.sleep(1000); // Waiting for 1 second before starting next thread
		Thread t2 = new Thread(rc);
		t2.start();
		Thread.sleep(1000); // Waiting for 1 second before starting next thread
		Thread t3 = new Thread(rc);
		t3.start();

		// Creating new instance for every thread access.
		ExtendsThread tc1 = new ExtendsThread();
		tc1.start();
		Thread.sleep(1000); // Waiting for 1 second before starting next thread
		ExtendsThread tc2 = new ExtendsThread();
		tc2.start();
		Thread.sleep(1000); // Waiting for 1 second before starting next thread
		ExtendsThread tc3 = new ExtendsThread();
		tc3.start();
	}
}

执行结果输出如下:

ImplementsRunnable : Counter : 1
ImplementsRunnable : Counter : 2
ImplementsRunnable : Counter : 3
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1
ExtendsThread : Counter : 1

In the Runnable interface approach, only one instance of a class is being created and it has been shared by different threads. So the value of counter is incremented for each and every thread access.

Whereas, Thread class approach, you must have to create separate instance for every thread access. Hence different memory is allocated for every class instances and each has separate counter, the value remains same, which means no increment will happen because none of the object reference is same.

 

Which one is best to use?

Ans : Very simple, based on your application requirements you will use this appropriately. But I would suggest, try to use interface inheritance i.e., implements Runnable.

 


 

转载于:https://www.cnblogs.com/CBDoctor/p/5077981.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值