java多线程机制中的Thread和Runnable()区别
1、java语言使用Thread类及其子类对象来表示线程,新建的一个线程声明周期中经历 新建、(声明一个线程,此时他已经有了相应的内存空间和其他资源),运行(线程创建之久就据用了运行的条件,一旦轮到使用CPU,此线程就会脱离创建他的主线程开始自己使命。此线程调用start()方法。通知JVM,这样JVM就会知道一个新的线程排队等候了。子类线程中必须重写Thread父类中的run方法,不然会发生异常。)。线中断机制,就是此线程使用Thread中的方法 sleep(int millsecond)此时线程会方法中断。经过millsecond后继续到CPU中排队等候。线程使用wait()方法。发生等待,等待状态的线程不会主动进入CPU等待序列,除非其他线程调用 notify()方法唤醒,使得他重新进入到CPU的等待序列,从中断处继续运行。线程死亡(所谓线程死亡就是该线程放弃了线程对象的内存)发生线程死亡的原因主要有两个,一是:线程运行完毕,结束了线程的run()方法。另一个原因是:线程被强制终止。
public class BinFa {
public static void main(String[] args) {
// TODO Auto-generated method stub
SpeakElephent elephent;
SpeakCar car;
elephent=new SpeakElephent();
car=new SpeakCar();
elephent.start();
car.start();
for(int i=0;i<=10;i++){
System.out.println("主人"+i+" ");
}
}
}
interface ShuZu{
String a[]={"花花","丽丽","小洁","明明","亚明"};
void Test( );
}
class SpeakElephent extends Thread implements ShuZu{
public void run(){
for(String i:a){
System.out.println("大象"+i);
}
}
public void Test(){
System.out.println("这是线程大象");
}
}
class SpeakCar extends Thread implements ShuZu{
public void run(){
for(String i:a){
System.out.println("汽车"+i);
}
}
public void Test(){
System.out.println("这是线程汽车");
}
}
2、线程调度和优先级问题
在线程机制中,调整线程的优先级还可以通过方法 setPriority(int grade )方法设置线程的优先级。但是在实际的的设置中应该假设,线会随时被剥夺CPU的使用权限,不能仅靠设置线程的优先权决定查询的正确执行。JVM中存在线程的管理机制。负责管理线程的调度顺序。
3、Thread和Runnable区别,启动main的时候,java虚拟机启动一个进程,主进程main在main()的调用的时候创建,但是start()方法调用后并不是立即执行多线程代码,而是使得该线程变成了可运行态(runnable),至于什么时候运行是由系统决定的。其中Thread.sleep()方法的调用只是为了不让抢钱的线程不单独霸占CPU资源。留出一定的时间非其他的线程。如果一个类继承Thread,则不适合资源共享,但是如果实现了Runnable接口的话,实现资源共享就很容易。,想要创建一个线程可运行实例,需要实现Runnable接口或者继承Thread类,Runnable只有一个抽象的Run()方法。可以这样说java中的线程只是操作系统中的的一个映射。java中的线程运行效率不可能高于底层语言的效率。这是因为java中的线程的创建和调用都要进过JVM,JVM再向下调用。
这里附上java.lang.Runnable源码
java.lang
Interface Runnable
- All Known Subinterfaces:
- RunnableFuture<V>, RunnableScheduledFuture<V>
- All Known Implementing Classes:
- AsyncBoxView.ChildState, FutureTask, RenderableImageProducer, SwingWorker, Thread, TimerTask
public interface Runnable
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.
This interface is designed to provide a common protocol for objects that wish to execute code while they are active. For example, Runnable is implemented by class Thread. Being active simply means that a thread has been started and has not yet been stopped.
In addition, Runnable provides the means for a class to be active while not subclassing Thread. A class that implements Runnable can run without subclassing Thread by instantiating a Thread instance and passing itself in as the target. In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Threadmethods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.
| Method Summary | |
|---|---|
void |
run() When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread. |
| Method Detail |
|---|
run
void run()
- When an object implementing interface
Runnableis used to create a thread, starting the thread causes the object'srunmethod to be called in that separately executing thread.The general contract of the method
runis that it may take any action whatsoever. -
- See Also:
Thread.run()
public class XianChengTongBu {
public static void main(String[] args) {
// TODO Auto-generated method stub
EleTarget t=new EleTarget();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
class EleTarget implements Runnable{
private int ticket=10;
public synchronized void run(){
for(int i=0;i<=10;i++){
if(this.ticket>0){
System.out.println("买票"+this.ticket--);
}
}
}
}
4、Runnable方法实现线程机制
public class GongXiangDanYan {
public static void main(String[] args) {
// TODO Auto-generated method stub
House house=new House();
house.setWater(10);
Thread dog,cat;
dog=new Thread(house);
cat=new Thread(house);
dog.setName("Dog");
cat.setName("Cat");
dog.start();
cat.start();
}
}
class House implements Runnable{
int wateAmount;
public void setWater(int w){
wateAmount=w;
}
public void run(){
while(wateAmount>=0){
String name=Thread.currentThread().getName();//得到当前线程的对象名字
if(name.equals("Dog")){
System.out.println(name+"Drink");
wateAmount=wateAmount-2;
}else if(name.equals("Cat")){
System.out.println(name+"Drink");
wateAmount=wateAmount-1;
}
System.out.println("left"+wateAmount);
try{
Thread.sleep(2000);
}catch(InterruptedException ex){
if(wateAmount<=0){
return;
}
}
}
}
}
5、线程中常见的方法,start(),run(), sleep(int millsecond) ,isAlive(), currentThread(), interrupt()
public class CurrentThread {
public static void main(String[] args) {
// TODO Auto-generated method stub
Home home=new Home();
Thread showTime=new Thread(home);
showTime.start();
}
}
class Home implements Runnable{
int time;
SimpleDateFormat m=new SimpleDateFormat("hh:mm:ss");
Date date;
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
date=new Date();
System.out.println(m.format(date));
time++;
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
if(time==4){
Thread thread=Thread.currentThread();
thread=new Thread(this);
thread.start();
}
}
}
}
}
interrupt()方法
public class ThreadGuanXi {
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassRoom room=new ClassRoom();
room.student.start();
room.teacher.start();
}
}
class ClassRoom implements Runnable{
Thread student,teacher;
ClassRoom(){
teacher=new Thread(this);
student=new Thread(this);
teacher.setName("冯涛");
student.setName("陈武阳");
}
public void run(){
if(Thread.currentThread()==student){
try{
System.out.println(student.getName()+"***********在睡觉************");
Thread.sleep(1000*60);
}catch(InterruptedException ex){
System.out.println("被"+teacher.getName()+"老师叫醒啦");
}
}
else if(Thread.currentThread()==teacher){
for(int i=0;i<3;i++){
System.out.println("###################上课#########");
try{
Thread.sleep(500);
}catch(InterruptedException ex){
}
student.interrupt();
}
}
}
}
6、线程同步问题,多个线程调用synchronize必须遵循同步机制
java多线程机制中的Thread和Runnable()区别的更多相关文章
- 最简单的java多线程代码(重写thread或者runnable的run方法)
http://blog.csdn.net/testcs_dn/article/details/42526549 java线程使用示例——最简单的线程 线程使用示例一: [java] view plai ...
- Java多线程(一) Thread和 Runnable
http://www.cnblogs.com/lwbqqyumidi/p/3804883.html 1.继承Thread 2.实现Runnable接口 public class MyRunnable ...
- “全栈2019”Java多线程第十章:Thread.State线程状态详解
难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...
- Linux内存管理机制中buffer和cache的区别
Linux内存管理机制中buffer和cache的区别理解linux内存管理,需要深入了解linux内存的各个参数含义和规则,下面介绍一下Linux操作系统中内存buffer和cache的区别. Fr ...
- 【Java多线程系列二】Thread类的方法
Thread实现Runnable接口并实现了大量实用的方法. /* * 此方法释放CPU,但并不释放已获得的锁,其它就绪的线程将可能得到执行机会,它自己也有可能再次得到执行机会 */ public s ...
- jdk1.8源码Thread与Runnable区别
一.概念 Thread实现了Runnable接口 public class Thread implements Runnable { /* Make sure registerNatives is t ...
- Java多线程-run方法与start方法的区别
package com.interview; /** * java多线程的两种实现方式以及run.start方法的区别 * @author MEI.LIU * */ public class Thre ...
- Java:多线程,分别用Thread、Runnable、Callable实现线程
并发性(concurrency)和并行性(parallel)是两个概念,并行是指在同一时刻,有多条指令在多个处理器上同时执行:并发指在同一时刻只能有一条指令执行,但多个进程指令被快速轮换执行,使得宏观 ...
- Java 多线程实现方式二:实现 Runnable 接口
由于java是单继承,很多时候为了实现多线程 通过继承 Thread 类后,就不能再继承其他类了.为了方便可以通过实现 Runnable 接口来实现,和Tread 类似需要重写run 方法. 下面通过 ...
随机推荐
- springboot-全局异常处理类
@ControllerAdvice public class GlobalExceptionHandler(){ @ExceptionHandler(value=Exception.class) @R ...
- excel数据有隐藏字符导致正则校验不通过
问题现象: 原因: 肉眼看不出任何问题,实际原因“有问题的”待校验字符串第一个单引号和第一个数字之间有个不可见字符 (注:Chrome控制台.常见编辑器定位光标 “Backspace退格删除”时,第一 ...
- Expression知识
http://www.cnblogs.com/Ninputer/archive/2009/08/28/expression_tree1.html#!comments
- 委托(作用:解耦),lambda的演化
1.了解委托 MyDelegate类代码如下: using System; using System.Collections.Generic; using System.Linq; using Sys ...
- 【.net ajax显示后台返回值】
1..net ajax显示后台返回值 <script> $(document).ready(function () { $("#btn&quo ...
- Javascript入门(三)函数
Javascript函数 一.函数定义与执行 <script type="text/javascript"> //define function fun1(){ ale ...
- Maven 传递依赖冲突解决(了解)
1 传递依赖冲突解决(了解) 传递依赖:A(项目)依赖B,B依赖C(1.1版本),B是A的直接依赖,C就是A的传递依赖 导入依赖D,D依赖C(1.2版本) 1.1 Maven自己调解原则 1.1.1 ...
- 关于 tp5.0 阿里云 oss 上传文件操作
tp5.0 结合阿里云oss 上传文件 1.引入 oss 的空间( composer install 跑下第三方拓展包及核心代码包) 备注:本地测试无误,放到线上有问题 应该是移动后的路劲(相对于服 ...
- Linxu基础知识:终端、终端模拟器、shell
实验楼课程第二个实验的讲解部分出现了三个词,我不知道它们三个是什么关系.查阅了度娘,归纳如下: - 终端: 在UNIX/LINUX系统中,用户通过终端登录系统后得到一个Shell进程,这个终端就成为S ...
- CVE-2019-0797漏洞:Windows操作系统中的新零日在攻击中被利用
https://securelist.com/cve-2019-0797-zero-day-vulnerability/89885/ 前言 在2019年2月,卡巴实验室的自动漏洞防护(AEP)系统检测 ...