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.ChildStateFutureTaskRenderableImageProducerSwingWorkerThreadTimerTask

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.

Since:
JDK1.0
See Also:
ThreadCallable

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 Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

The general contract of the method run is 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()区别的更多相关文章

  1. 最简单的java多线程代码(重写thread或者runnable的run方法)

    http://blog.csdn.net/testcs_dn/article/details/42526549 java线程使用示例——最简单的线程 线程使用示例一: [java] view plai ...

  2. Java多线程(一) Thread和 Runnable

    http://www.cnblogs.com/lwbqqyumidi/p/3804883.html 1.继承Thread 2.实现Runnable接口 public class MyRunnable ...

  3. “全栈2019”Java多线程第十章:Thread.State线程状态详解

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java多 ...

  4. Linux内存管理机制中buffer和cache的区别

    Linux内存管理机制中buffer和cache的区别理解linux内存管理,需要深入了解linux内存的各个参数含义和规则,下面介绍一下Linux操作系统中内存buffer和cache的区别. Fr ...

  5. 【Java多线程系列二】Thread类的方法

    Thread实现Runnable接口并实现了大量实用的方法. /* * 此方法释放CPU,但并不释放已获得的锁,其它就绪的线程将可能得到执行机会,它自己也有可能再次得到执行机会 */ public s ...

  6. jdk1.8源码Thread与Runnable区别

    一.概念 Thread实现了Runnable接口 public class Thread implements Runnable { /* Make sure registerNatives is t ...

  7. Java多线程-run方法与start方法的区别

    package com.interview; /** * java多线程的两种实现方式以及run.start方法的区别 * @author MEI.LIU * */ public class Thre ...

  8. Java:多线程,分别用Thread、Runnable、Callable实现线程

    并发性(concurrency)和并行性(parallel)是两个概念,并行是指在同一时刻,有多条指令在多个处理器上同时执行:并发指在同一时刻只能有一条指令执行,但多个进程指令被快速轮换执行,使得宏观 ...

  9. Java 多线程实现方式二:实现 Runnable 接口

    由于java是单继承,很多时候为了实现多线程 通过继承 Thread 类后,就不能再继承其他类了.为了方便可以通过实现 Runnable 接口来实现,和Tread 类似需要重写run 方法. 下面通过 ...

随机推荐

  1. linux 查看文件夹大小

    参考链接:  http://www.cnblogs.com/iconfig/p/4863063.html

  2. 【mmall】mybatis三剑客

    mybatis-generator mybatis-plugin Mybatis Plugin插件安装破解及使用:http://blog.csdn.net/u011410529/article/det ...

  3. Maven多模块项目管理小结

    原文地址:http://blog.csdn.net/whuslei/article/details/7989102 题记 最近刚完成一个用Maven构建的Web项目,看了一些Maven方面的书,比如& ...

  4. python - psutil 系统信息模块

    # .psutil是一个跨平台库能够轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等)信息. # 它主要用来做系统监控,性能分析,进程管理. # 它实现了同等命令行工具提供的功能 ...

  5. 20165337岳源 第四次实验 Android开发

    1.实验要求: 参考<Java和Android开发学习指南(第二版)(EPUBIT,Java for Android 2nd)>第二十四章 参考http://www.cnblogs.com ...

  6. oracle-----视图/物化视图

    什么是视图 视图(view),也称虚表, 不占用物理空间,这个也是相对概念,因为视图本身的定义语句还是要存储在数据字典里的. 视图只有逻辑定义.每次使用的时候,只是重新执行SQL. 视图是从一个或多个 ...

  7. Hibernate学习(三)

    Hibernate的查询方法(五种) 一.OID查询:按主键查询 --get( ) --load( ) 二.对象导航查询:通过已经查询到的联系人,得到起关联的对象 三.SQL查询 四.HQL查询(** ...

  8. 编程基础 - 0x00008 的0x代表什么?

    总结: 二进制:0dXXXX 八进制:0XXXX 十六进制:0xXXXX ------------------------------- 1- 十六进制 以“0x”开始的数据表示16进制,计算机中每位 ...

  9. 2018 “百度之星”程序设计大赛 - 初赛(A)

    第二题还算手稳+手快?最后勉强挤进前五百(期间看着自己从两百多掉到494名) 1001  度度熊拼三角    (hdoj 6374) 链接:http://acm.hdu.edu.cn/showprob ...

  10. GeoDesc: Learning Local Descriptors by Integrating Geometry Constraints

    这篇论文提出了一种新的局部描述子学习方法,有一些点值得学习,记录下来以供参考.文章中涉及了一些3D reconstruction.structure from 的知识,不是很了解,所以理解可能有偏颇. ...