一提到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. Mysql基础1

    一.数据库简介1.Structured Query Language (结构化查询语言)2.SQL:工业标准.(各个数据库厂商都支持)SQL-Server:对标准进行了扩展.TSQL 方言Oracle ...

  2. Pig Hive对比(zz)

    Pig Latin:数据流编程语言 一个Pig Latin程序是相对于输入的一步步操作.其中每一步都是对数据的一个简单的变换. 用Pig Latin编程更像在RDBMS中“查询规划器”(query p ...

  3. Silverlight C1.Silverlight.FlexGrid 表格动态列

    很多时候,我们对于表格展示的数据,需要根据条件不停的变化,这就需要表格列能动态生成,即没有Model的概念(万物始于无形).先上主要代码: 一.根据参数绑定列定义 二.根据数据动态创建数据对象,并添加 ...

  4. java去处重复输出

    去除重复输出问题:   数组:大量相同数据类型的集合 数据类型[ ] 数组名=new 数据类型[长度] 数据类型[ ] 数组名=new 数据类型[ ]{值1,值 2,值3.....} 数据类型[ ] ...

  5. 【JSP】Tiles框架的基本使用

    Tiles介绍 Tiles 是一种JSP布局框架,主要目的是为了将复杂的jsp页面作为一个的页面的部分机能,然后用来组合成一个最终表示用页面用的,这样的话,便于对页面的各个机能的变更及维护. Tile ...

  6. oop第二章1知识点汇总

    1 方法重写必须满足以下要求: 1 重写方法与被重写的方法必须方法名相同,参数列表相同. 2 重写方法与被重写的方法返回值类型必须相同或是其子类 3 重写方法不能缩小被重写方法的访问权限 2 重载和重 ...

  7. C++ 优先队列

    C++ 优先队列 #include <queue> priority_queue<Type, Container, Functional>:Type为数据的类型,Contain ...

  8. 从原生APK反编译,拿到界面,用于mono for android

    从原生APK反编译,拿到界面,用于mono for android 1.用apktool反编译apk,得到xxx.apk.de 2.从xxx.apk.de\res\layout 3.复制所有xml到M ...

  9. plsql基础

    语法:declare-->声明变量 begin-->执行部分 exception-->异常 end-->结束 / 最简单的程序:begin null; end; 输出语句:DB ...

  10. JSON相关(一):JSON.parse()和JSON.stringify()

    parse用于从一个字符串中解析出json对象,如 var str = '{"name":"huangxiaojian","age":&qu ...