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.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必须遵循同步机制

原文地址:https://www.cnblogs.com/xinxianquan/p/8810713.html