[转]Java中Runnable和Thread的区别(二)

Thread和Runnable的区别和联系 Thread和Runnable的区别和联系 在java中可有两种方式实现多线程,一种是继承Thread类,一种是实现Runnable接口。 一、Thread类 Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就可以实现多线程操作了,但是一个类只能继承一个父类,这是此方法的局限,下面看例子:  pu 阅读详情

 但是在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。此时观察Thread类,有一个构造方法:public Thread(Runnable targer)

  此构造方法接受Runnable的子类实例,也就是说可以通过Thread类来启动Runnable实现的多

  线程。(start()可以协调系统的资源):

  package org.runnable.demo;

  import org.runnable.demo.MyThread;

  public class ThreadDemo01 {

  public static void main(String[] args) {

  MyThread mt1=new MyThread("线程a");

  MyThread mt2=new MyThread("线程b");

  new Thread(mt1).start();

  new Thread(mt2).start();

  }

  }

  · 两种实现方式的区别和联系:

  在程序开发中只要是多线程肯定永远以实现Runnable接口为主,因为实现Runnable接口相比

  继承Thread类有如下好处:

  ->避免点继承的局限,一个类可以继承多个接口。

  ->适合于资源的共享

  以卖票程序为例,通过Thread类完成:

  package org.demo.dff;

  class MyThread extends Thread{

  private int ticket=10;

  public void run(){

  for(int i=0;i<20;i++){

  if(this.ticket>0){

  System.out.println("卖票:ticket"+this.ticket--);

  }

  }

  }

  };

  下面通过三个线程对象,同时卖票:

  package org.demo.dff;

  public class ThreadTicket {

  public static void main(String[] args) {

  MyThread mt1=new MyThread();

  MyThread mt2=new MyThread();

  MyThread mt3=new MyThread();

  mt1.start();//每个线程都各卖了10张,共卖了30张票

  mt2.start();//但实际只有10张票,每个线程都卖自己的票

  mt3.start();//没有达到资源共享

  }

  }

  如果用Runnable就可以实现资源共享,下面看例子:

  package org.demo.runnable;

  class MyThread implements Runnable{

  private int ticket=10;

  public void run(){

  for(int i=0;i<20;i++){

  if(this.ticket>0){

  System.out.println("卖票:ticket"+this.ticket--);

  }

  }

  }

  }

  package org.demo.runnable;

  public class RunnableTicket {

  public static void main(String[] args) {

  MyThread mt=new MyThread();

  new Thread(mt).start();//同一个mt,但是在Thread中就不可以,如果用同一

  new Thread(mt).start();//个实例化对象mt,就会出现异常

  new Thread(mt).start();

  }

  };

  虽然现在程序中有三个线程,但是一共卖了10张票,也就是说使用Runnable实现多线程可以达到资源共享目的。

  Runnable接口和Thread之间的联系:

  public class Thread extends Object implements Runnable

  发现Thread类也是Runnable接口的子类。

引用自:http://java.chinaitlab.com/line/820728_2.html

Java多线程实现之Thread和Runnable的区别 一、Runnable接口实现多线程解决了继承thread的单继承局限 二、Thread类是Runnable接口的子类,Thread类覆写了Runnable接口的run()方法 三、Runnable实现的多线程的程序类可以更好的描述出程序共享的概念 (1)使用Thread实现数据共享 class MyThread1 extends Thread { private int ... 阅读详情

相关推荐

Java中Runnable和Thread的区别

在我们开发的过程中常常会碰到多线程的问题,对于多线程的实现方式主要有两种:实现Runnable接口、继承Thread类。对于这两种多线程的实现方式也是有着一些差异。既然实现了多线程那必然离不开管理这些线程,当问题比简单时一个或者几个线程就OK了,也涉及不到效率问题。一旦线程数量多起来的时候,必然躲不过这些线程的创建与销毁,而往往这是很浪费时间的。这时就需要利用线程池来进行管理,既免去了我们创建线程...

人生代码 ---- 公众号 864

Thread 和 Runnable 的区别

今天在学习多线程的时候,了解了 创建线程的几种方式,然后就脑子发热,突然想到 Thread 和 Runnable 创建线程有什么区别吗?毕竟是长得都不一样。所以我就找了一些资料(优快云 大佬们的文章)来看看,有了一些理解。 明确一点:Runnable 和 Thread 本质上是没有区别的。 区别 如果非要说区别的话,那么就有一下几点 Runnable 和 Thread 创建线程的方式不一样 Runnable 是接口,Thread 是实体类,Thread 和 Runnable 的关系就是实体与实现.

就这样吧 4780

24届-Python面经(华为OD)

【摘要】24届非科班生通过栗栗姐指导成功转行华为OD。从4月4日零基础准备,经历机考(4/18)、测评(4/19)、资格面(5/7)、技术面(5/9-11)到5月17日获offer。全程栗栗姐提供题库、面经指导和实时跟进。虽遇压力面和技术短板,但在专业辅导下10天走完全流程。案例证明转行需自身努力+优质HR支持,栗栗姐团队提供多岗位(Java/Python等)、多地域(北上深等)OD机会,含笔试资料和全流程攻略。

2401_86909848的博客 1189

Thread和Runnable的区别

Thread 与Runnab le区别 博客分类: java 多线程ThreadRunnable  大家都知道多线程可以通过两种方式来创建。 一、通过继承Thread类 二、通过实现Runnable接口 那么中两种方式到底有什么区别呢?那种方式更好些呢? 我们使用多线程,无非就是想利用多线程的优点,来更好的实现我们的想法。 多线程有哪些优点呢? 一、多线程共享同

Search,Research 1万+

紫光同创PGL50H开发板实战:盘古50KN网口板的高速通信与数据处理

本文详细介绍了紫光同创PGL50H开发板(盘古50KN网口板)在高速通信与数据处理领域的实战应用。文章从开箱、核心芯片解析、开发环境搭建入手,重点讲解了如何配置与测试其8路千兆以太网接口和SFP光纤接口,并深入探讨了FPGA与DDR3协同进行多路数据汇聚处理的系统架构与调试方法,为网络通信与高速数据处理系统开发提供了宝贵的实践经验。

weixin_28256233的博客 455

别再死磕文档了!用国产MBSES软件5分钟上手MBSE建模(保姆级图文教程)

本文通过国产MBSES软件,详细演示了如何在5分钟内完成智能家居系统的MBSE建模。从模块图定义到状态机图构建,再到参数约束验证,全程图文指导,帮助工程师快速掌握基于模型的系统工程方法,显著提升复杂系统设计效率。

weixin_26833503的博客 245

Java里Thread和Runnable区别?

在Java中,Thread和Runnable是实现多线程的两种主要方式,但它们在使用和功能上有显著差异。Thread是一个类,通过继承并重写run()方法来定义线程逻辑,每次启动线程需调用start()方法,但受限于Java的单继承特性,灵活性较低。相比之下,Runnable是一个接口,通过实现run()方法定义任务逻辑,再由Thread对象启动线程,支持多重继承,更适合多线程共享任务。此外,Runnable与线程池的兼容性更好,能够更有效地管理资源。因此,推荐使用Runnable,尤其是在需要线程池或资源

weixin_46072507的博客 711

用长tree方式做等长线

1)写一个sdc,把等长线的起点设置成clock source,用于创建create_clock,至于period和waveform等参数随便写即可。然后clock_opt -from build_clock -to route_clock即可。3)在正式cts之前或之后,给自己创建的scenario长tree并don't touch。前面讲过了如何用set_data_check做等长线,这里再讲一下如何用cts的方式做。2)为该clock创建一个新mode,并创建对应的scenario。

m0_61544122的博客 623

Runnable 和 Thread 有什么区别

线程状态:创建Thread对象后,可以直接调用start()方法启动线程,而使用Runnable需要先创建Thread对象,然后将Runnable对象传递给Thread对象,最后调用start()方法启动线程。如果需要对线程类进行自定义的扩展,例如重写Thread类的方法来改变线程的行为,那么继承Thread类就是一个不错的选择。继承性:Thread是一个类,因此如果继承Thread类,子类就不能再继承其他的类了,而实现Runnable接口可以继承其他类,这样可以避免Java中单继承带来的限制。

qq_30667039的博客 4391

基于ESP32的智能车载环境监测系统开发

随着智能汽车技术的飞速发展,车载系统的功能越来越多样化,除了基本的行驶控制和娱乐功能外,车载环境监测系统也成为了一项重要的功能。通过实时监测车内环境数据,例如温度、湿度、空气质量、气体浓度等,智能车载环境监测系统能够提供更为舒适和安全的驾驶体验,同时增强车辆的智能化程度,提升用户的整体体验。ESP32作为一种集成了Wi-Fi和蓝牙功能的高效能低功耗嵌入式开发平台,成为了设计车载环境监测系统的理想选择。它不仅具备丰富的接口和处理能力,还能够实现与云平台、手机应用等系统的远程数据传输和控制。

2201_76125393的博客 715

基于多智能体强化学习的轨道追逃博弈方法复现

本文提出了一种基于多智能体深度强化学习(MADDPG)的空间轨道追逃博弈方法。通过构建Actor-Critic网络架构,采用集中训练分布式执行的策略,使卫星群能够自主协调完成对非合作目标的围捕任务。代码实现了经验回放缓冲区、噪声探索机制和网络参数更新等核心功能,通过奖励函数设计平衡最短时间、燃料消耗和碰撞规避等目标。仿真结果表明该方法能有效利用数量优势,涌现出智能协同行为,为解决复杂空间博弈问题提供了新思路。

huanghm88的专栏 337

java thread和runnable_java中thread和runnable的区别

展开全部线程的起动62616964757a686964616fe4b893e5b19e31333361326332并不是简单的调用了你的RUN方法,而是由一个线程调度器来分别调用你的所有线程的RUN方法,我们普通的RUN方法如果没有执行完是不会返回的,也就是会一直执行下去,这样RUN方法下面的方法就不可能会执行了,可是线程里的RUN方法却不一样,它只有一定的CPU时间,执行过后就给别的线程了,这样...

weixin_35666639的博客 1065

基于STM32L4XX、HAL库的ICM-42670-P姿态传感器驱动程序设计

sprintf(buffer, "温度: %.1f °C\r\n\r\n", sensor_data.temperature);sprintf(buffer, "陀螺仪: X=%.2f Y=%.2f Z=%.2f rad/s\r\n",sprintf(buffer, "加速度: X=%.2f Y=%.2f Z=%.2f m/s²\r\n",sprintf(buffer, "开始校准IMU,请保持传感器静止...\r\n");sprintf(buffer, "读取传感器数据失败\r\n");

zhusl6688的博客 643

Java源码之深入解析Runnable和Thread的区别

我们都知道创建一个线程有两种方式一是继承Thread,一是实现Runnable接口。 那么java面试基本必问的一个问题就是这两种方式有什么区别。 其实区别有很多,简单讲Thread类本身也是实现了Runnable接口的。 所以继承了Thread类的线程类 都拥有实现Runnable接口的基本特性,但是实现了Runnable接口的线程类却不一定有Thread类的一些特性。 看看源码吧更清晰一点: ...

Phoenix_smf的博客 576

智能硬件产品:做好一款电子硬件产品,工具必不可少

上到战略规划,中至运营策略,下至人性洞察,。最初做产品时,笔者从一开始就陷入到了对工具的痴迷,包括:PS、AutoCAD、PROE、犀牛、Axure、Keyshot、Altium……大概将 2 个多月的时间和精力都消耗在了学习使用工具上。通过工具的运用也确实提高了工作效率,在仅有创意的前提下通过灵活运用工具,一年内便成功申请了多个实用新型专利、设计了多款产品的高保真原型图等。正在上传…重新上传取消。

产品线负责人 1446

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Thread和Runnable区别

(实现Runnable接口),代码如下: Thread和Runnable代码的区别:

酷小亚 2220

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Java线程中,Thread和Runnable创建线程的区别

一、Thread创建线程,通过新建类继承Thread类,重写run方法,然后在main方法中start(),创建并启动线程. public class MyThread extends Thread{//除了构造方法和私有属性其他的都可以被继承下来 @Override//重写了父类Thread的run方法. //在main方法start()创建并启动线程时,会调用此方法. pu...

Doppelganger 2771

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

上一篇: [转]Java中Runnable和Thread的区别(一)
下一篇: [转]使用XStream把Java对象序列化为XML(一)
mxbin2008
博客等级 码龄19年 16粉丝 76原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值