一提到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.

Java 多线程(1)-Thread和Runnable的更多相关文章

  1. java 多线程:Thread类;Runnable接口

    1,进程和线程的基本概念: 1.什么是进程: 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在早期面向进程设计的计算机 ...

  2. java多线程(二)之实现Runnable接口

    一.java多线程方式2: 实现Runnable接口 好处:a. 可以避免由于java单继承带来的局限性. b. 适合多个相同的程序的代码去处理同一个资源的情况, 把线程与程序的代码, 数据有效分离, ...

  3. JAVA多线程(一) Thread & Runnable

    githut代码地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service/ ...

  4. Java多线程01(Thread类、线程创建、线程池)

    Java多线程(Thread类.线程创建.线程池) 第一章 多线程 1.1 多线程介绍 1.1.1 基本概念 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于 ...

  5. java线程(上)Thread和Runnable的区别

    首先讲一下进程和线程的区别: 进程:每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有较大的开销,一个进程包含1--n个线程. 线程:同一类线程共享代码和数据空间,每个线程有独立的运行栈 ...

  6. Java 多线程(Thread)学习

    多线程:就是进程的扩展,实现并发.一个进程可以包含多个线程,进程一般是由操作系统控制,而线程就是由程序员控制的,所以作为编程人员做好线程是我们的重点. 线程和进程一样分为五个阶段:创建.就绪.运行.阻 ...

  7. Java 多线程 socket 取款例子 runnable callable

    socket部分参考 http://blog.csdn.net/kongxx/article/details/7259465 取款部分参考 http://blog.csdn.net/dayday198 ...

  8. 并发编程之多线程基础-Thread和Runnable的区别及联系(二)

    上篇文章讲述了创建线程的常用方式 本篇主要分析一下Thread和Runnable两种方式创建线程的区别及联系 联系: ▶Thread类实现了Runable接口. ▶都需要重写里面Run方法. 区别: ...

  9. java多线程创建-Thread,Runnable,callable和threadpool

    java创建多线程的方式有许多种,这里简要做个梳理 1. 继承Thread类 继承java.lang.Thread类,创建本地多线程的类,重载run()方法,调用Thread的方法启动线程.示例代码如 ...

随机推荐

  1. db2 怎么计算两个时间相差多少个月。如2015-10-10 和2014-1-12

    SELECT timestampdiff (256, char(timestamp('2013-12-30 20:30:30') - timestamp('2001-09-26 15:24:23')) ...

  2. Backbone.js入门教程

    原文: Getting Started with Backbone.js 不像其它的Web开发语言,过去Javascript很少可用的架构.令人感到高兴的是,最近几年这种情况得到非常大的改善. 今天我 ...

  3. 斯坦福第十七课:大规模机器学习(Large Scale Machine Learning)

    17.1  大型数据集的学习 17.2  随机梯度下降法 17.3  微型批量梯度下降 17.4  随机梯度下降收敛 17.5  在线学习 17.6  映射化简和数据并行 17.1  大型数据集的学习

  4. SQLServer的Login迁移脚本

    背景:公司的数据由SQLServer2008 R2升级至SQLServer2012,并配置了AlwaysOn,本脚本用于将主节点的Login迁移至辅助节点. 1.在主节点执行以下脚本创建存储过程: U ...

  5. ASP.NET MVC请求处理管道生命周期的19个关键环节(13-19)

    在上一篇"ASP.NET MVC请求处理管道生命周期的19个关键环节(7-12) ",体验了7-12关键环节,本篇继续. ⒀当请求到达UrlRoutingModule的时候,Url ...

  6. C#,Java,C -循环冗余检验:CRC-16-CCITT查表法

    C#代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ...

  7. BlueDream.js(蓝梦)——jQuery网站使用引导插件

    小菜在前端世界游荡有些时间了,常见的插件多少有些了解,但却很少看到用户引导插件. 所谓用户引导插件,就是在第一次使用某个网站时,会弹出一些小动画,告诉你网站的基本使用方法,帮你快速入门. 这应该是个常 ...

  8. php性能分析工具 - xhprof的安装使用

    一.前言 有用的东西还是记录下来吧,也方便以后的查询:这次记录一下xhprof的安装使用: xhprof是facebook开源出来的一个php轻量级的性能分析工具,跟Xdebug类似,但性能开销更低, ...

  9. Ajax初步理解

    最近在项目中经常会使用Ajax技术,用法上倒是熟练了,但是只知其然,不知其所以然,抽时间读了读JavaScript高级程序设计中关于Ajax的介绍有了些初步的理解,在此总结一下. 什么是Ajax Aj ...

  10. VS2015详细安装步骤

    亲身经历记录下来,以备后用.也希望能够帮助到有需要的朋友们! 1.安装之前首先下载VS2015,下载地址: [VS2015社区版官方中文版下载]:http://download.microsoft.c ...