Java 多线程(1)-Thread和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.
Java 多线程(1)-Thread和Runnable的更多相关文章
- java 多线程:Thread类;Runnable接口
1,进程和线程的基本概念: 1.什么是进程: 进程(Process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础.在早期面向进程设计的计算机 ...
- java多线程(二)之实现Runnable接口
一.java多线程方式2: 实现Runnable接口 好处:a. 可以避免由于java单继承带来的局限性. b. 适合多个相同的程序的代码去处理同一个资源的情况, 把线程与程序的代码, 数据有效分离, ...
- JAVA多线程(一) Thread & Runnable
githut代码地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo/spb-brian-query-service/ ...
- Java多线程01(Thread类、线程创建、线程池)
Java多线程(Thread类.线程创建.线程池) 第一章 多线程 1.1 多线程介绍 1.1.1 基本概念 进程:进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于 ...
- java线程(上)Thread和Runnable的区别
首先讲一下进程和线程的区别: 进程:每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有较大的开销,一个进程包含1--n个线程. 线程:同一类线程共享代码和数据空间,每个线程有独立的运行栈 ...
- Java 多线程(Thread)学习
多线程:就是进程的扩展,实现并发.一个进程可以包含多个线程,进程一般是由操作系统控制,而线程就是由程序员控制的,所以作为编程人员做好线程是我们的重点. 线程和进程一样分为五个阶段:创建.就绪.运行.阻 ...
- Java 多线程 socket 取款例子 runnable callable
socket部分参考 http://blog.csdn.net/kongxx/article/details/7259465 取款部分参考 http://blog.csdn.net/dayday198 ...
- 并发编程之多线程基础-Thread和Runnable的区别及联系(二)
上篇文章讲述了创建线程的常用方式 本篇主要分析一下Thread和Runnable两种方式创建线程的区别及联系 联系: ▶Thread类实现了Runable接口. ▶都需要重写里面Run方法. 区别: ...
- java多线程创建-Thread,Runnable,callable和threadpool
java创建多线程的方式有许多种,这里简要做个梳理 1. 继承Thread类 继承java.lang.Thread类,创建本地多线程的类,重载run()方法,调用Thread的方法启动线程.示例代码如 ...
随机推荐
- 浪潮不能进bios解决过程
开机时会有个提示一闪而过,经过拍摄视频观看发现是"Press DEL to SETUP or TAP to post" 但是,反复重启不停按Delete键都无效,都进入了Ctrl+ ...
- lab 7 函数超级多的类
#include<iostream>#include<string>#include<cmath>using namespace std; class Ration ...
- Mac mysql修改密码
在网上看了很多的办法,其实解决办法都对,只是没有说明白: 1,首先启动mysql服务 2,mysqladmin -uroot -p 'newpassword' 此时需要输入登陆密码(数据库的密码,刚安 ...
- 【动态规划】bzoj1669 [Usaco2006 Oct]Hungry Cows饥饿的奶牛
#include<cstdio> #include<algorithm> using namespace std; int n,a[5001],b[5001],en; int ...
- MySQL数据库小实验
实验1 1.创建数据表 CREATE TABLE guest( Accounts ) NOT NULL, Details ) NOT NULL, Date ) NOT NULL, ,), Class ...
- 添加ModelGoon插件Eclipse自动生成UML图
下载ModelGoonjar包 http://download.csdn.net/detail/u011070297/8366021 下载完该jar之后,直接拷贝到Eclipse安装目录下的dropi ...
- 在Ubuntu全局安装express报错:Error: EACCES, mkdir '/usr/lib/node_modules/express'的解决办法
$ npm install -g express npm ERR! Error: EACCES, mkdir '/usr/lib/node_modules/express' npm ERR! { [E ...
- 利用扩展事件(Xevents)捕捉高消耗查询
生产环境中有时需要使用者抓取一些特定的语句分析,如超超长查询,或高IO查询等.一般来说大家对跟踪比较熟悉,主要因为其有完善的UI支持.由于扩展事件在sql2012才提供UI支持,所以虽然在08时就已经 ...
- [OpenGL] 1、环境搭建及最小系统
>_<: 首先推荐一个企业版的VC6.0自带OpenGL和DirectX,非常方便:http://pan.baidu.com/s/1mgIAGi8 PS: 要注意这里的OpenGL建立的工 ...
- 使用SharePoint CSOM 编写高效的程序
上一篇文章中简单的介绍了使用CSOM进行编程.今天主要讲一下CSOM使用中一些小技巧,可以让你的程序运行的更快. 单独加载某些属性 在上文中的例子,需要返回Web对象信息的时候,我们使用了如下的代码: ...