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 方法. 下面通过 ...
随机推荐
- jsonp实现下拉搜索
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- P1903 [国家集训队]数颜色 / 维护队列(莫队区间询问+单点修改)
题目链接:https://www.luogu.org/problemnew/show/P1903 题目大意:中文题目 具体思路:莫队单点修改+区间询问模板题,在原来的区间询问的基础上,我们要记录当前这 ...
- mysql 案例 ~ mysql常见日志错误
一 简介: mysql note级别日志汇总二错误系列 1 Aborted connection 1 [Note] Aborted connection 61 to db: 'unconnec ...
- zabbix系列 ~ 报警模式
一 简介:聊聊zabbix的报警方式二 报警方式 邮件,短信,钉钉,微信三 准备 需要预选准备好对应报警方式的脚本四 web端设置 1 设置报警方式 2 设置报警触发器 1 选择报警信息 ...
- Javascript - Jquery - 事件
事件(Event) 文档事件 文档的载入事件 ready(fn) $(document).ready(function () { }); //或$(function () {}); //或$(docu ...
- 在Linux环境下使用Jexus部署ASP.NET Core
关于如何在Linux中添加ASP.NET Core运行时环境请参考我的上一篇文章,本文章将不再做赘述. 本文章运行环境如下: (1) 安装独立版Jexus 本教程安装的是独立版的Jexus,独立版的 ...
- HTML5 头部【快速编写】
<!doctype html> <html><head> <meta charset="utf-8">#设置网页文件展示时使用的字符 ...
- Tomcat安装7.0.91
版本升级,JDK 1.7,Tomcat从7.0.73升级到7.0.91 为什么升级?解决安全漏洞! 升级就正常流程,下载*.tar.gz ,解压,改配置. 但碰到神奇的坑: 1.server.xml中 ...
- Django 中的 model 继承
Django 中的 model 继承和 Python 中的类继承非常相似,只不过你要选择具体的实现方式:让父 model 拥有独立的数据库:还是让父 model 只包含基本的公共信息,而这些信息只能由 ...
- mysql的group by查询
下面是多种写法,针对使用group by后得到最新记录的测试及结果: 说明:我在测试的时候,因为我的表数据在增加,得到最新的数据可能不同 -- 1.得到每个分组中id最小的那条记录 select * ...