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 方法. 下面通过 ...
随机推荐
- 【blog】MySQL中tinytext、text、mediumtext和longtext详解
参考链接 http://www.cnblogs.com/pureEve/p/6015000.html
- Git命令执行漏洞
Git命令造成的反弹shell 漏洞描述: Git LFS可以.lfsconfig使用LFS由存储库中的文件配置(部分),并且可以将Git LFS指向ssh://. [lfs] url = ssh:/ ...
- SQL 删除的三个语句:DROP、TRUNCATE、 DELETE 的区别
转载:http://www.runoob.com/sql/sql-delete.html DROP: DROP test; 删除表test,并释放空间,将test删除的一干二净. TRUNCATE: ...
- 2017-2018-2 20165231 实验三 敏捷开发与XP实践
实验报告封面 课程:Java程序设计 班级:1652班 姓名:王杨鸿永 学号:20165231 指导教师:娄嘉鹏 实验日期:2018年4月28日 实验时间:15:25 - 17:15 实验序号:实验三 ...
- Node.js安装和简介
Node.js是基于Chrome的V8 JavaScript引擎构建的JavaScript运行平台.Node.js 使用了一个事件驱动.非阻塞式 I/O 的模型,使其轻量又高效. Node.js 的包 ...
- HTTP协议03-http特点及请求方式
无状态: HTTP是一种不保存状态,既无状态协议.HTTP自身不对请求和响应之间的通信状态进行保存,也就是说不做持久化处理.这是为了更快处理大量事务,确保协议的可伸缩性. 随着web的不断发展,无状态 ...
- python3+requests库框架设计04-配置文件
python3配置文件的增删改查等操作可以使用内置的ConfigParser模块,可以自行百度学习,也可以看Python3学习笔记27-ConfigParser模块 配置文件一般存放着环境信息,比如u ...
- LSH(Locality Sensitive Hashing)原理与实现
原文地址:https://blog.csdn.net/guoziqing506/article/details/53019049 LSH(Locality Sensitive Hashing)翻译成中 ...
- FHQ Treap摘要
原理 以随机数维护平衡,使树高期望为logn级别 不依靠旋转,只有两个核心操作merge(合并)和split(拆分) 因此可持久化 先介绍变量 ; int n; struct Node { int v ...
- "贪吃蛇"-css3效果
clip : http://www.w3school.com.cn/cssref/pr_pos_clip.asp 姜糖水 : http://www.cnphp6.com/archives/60 ...