关于Thread与runnable

关于线程的的实现有两种,一种是实现Runnable接口,一种是继承Thread。最近深入了解了一下,做下笔记。

1. 首先一个问题是实现线程优先考虑用哪种方式实现?

优先考虑使用实现Runnable接口,原因如下:

a. java中只能实现单继承,有一定的局限性

2. 启动线程一定要通过start()方法,run()方法不能启动。

public class TestThreadInit {

    public static void main(String[] args) {
        //System.out.println("主线程:"+Thread.currentThread().getName());
        MyThread t = new MyThread("TESTTHREAD");
        t.start();
    }

    static class MyThread extends Thread{

        public MyThread(String string) {
            super(string);
        }

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName());
            System.out.println("测试");
        }
    }
}

上面的代码为正常启动线程,若将start方法换为run方法,输出的线程名都会变为主线程。jdk官方官方文档也有描述:

Causes this thread to begin execution; the Java Virtual Machine calls the <code>run</code> method of this thread.

run方法会通过虚拟机进行调用。

3. 多次调用start()方法会有什么影响?

这个可以通过源代码看出。

 1   public synchronized void start() {
 2         /**
 3      * This method is not invoked for the main method thread or "system"
 4      * group threads created/set up by the VM. Any new functionality added
 5      * to this method in the future may have to also be added to the VM.
 6      *
 7      * A zero status value corresponds to state "NEW".
 8          */
 9         if (threadStatus != 0 || this != me)
10             throw new IllegalThreadStateException();
11         group.add(this);
12         start0();
13         if (stopBeforeStart) {
14         stop0(throwableFromStop);
15     }
16     }

其中threadStatus 会记录线程状态,若多次调用此方法,会抛出IllegalThreadStateException。

4.Thread 与Runable联系

a. Thread 实现了Runable接口

public class Thread implements Runnable {}

在Thread类中引用了Runable

 /* What will be run. */
    private Runnable target;

Thread的构造函数函数都会调用init方法

public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}

public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}

private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize){}

run()方法实现

 public void run() {
    if (target != null) {
        target.run();
    }
    }

若使用extend方式创建线程,target对象为null,这时是通过调用重写继承Thread的子类run方法实现,若使用实现runable接口实现,是通过target对象的run方法实现 。

如有问题,请多多指教。

未完,待续。。。。。。。

  

时间: 2024-07-30 06:23:35

关于Thread与runnable的相关文章

Java - Thread 和 Runnable实现多线程

Java多线程系列--"基础篇"02之 常用的实现多线程的两种方式 概要 本章,我们学习"常用的实现多线程的2种方式":Thread 和 Runnable.之所以说是常用的,是因为通过还可以通过java.util.concurrent包中的线程池来实现多线程.关于线程池的内容,我们以后会详细介绍:现在,先对的Thread和Runnable进行了解.本章内容包括:Thread和Runnable的简介Thread和Runnable的异同点Thread和Runnable的

多线程——Thread与Runnable的区别

首先,从使用形式上,使用Runnable实现多线程更好,因为避免了单继承问题,但除了这一点之外,Thread和Runnable之间也存在一些联系.观察Thread类的定义形式: public class Threadextends Objectimplements Runnable 原来Thread类是Runnable接口的子类,那么Thread类也应该覆写了run()方法. @Override public void run() { if (target != null) { target.r

Thread 和Runnable的区别

Thread 和Runnable 的区别 Thread类 在java中可有两种方法实现度线程,一种是继承Thread类,一种是实现Runnable接口.Thread类是在java.lang包中定义的.一个类只要继承了Thread类,并覆写了本类的run()方法就可以实现多线程操作了,但是一个类只能继承一个父类,这就是此方法的局限性. 但是,此时结果很有规律,先是第一个对象执行,然后第二个对象执行,并没有相互运行.在JDK的文档中可以发现,一旦调用start()方法.下面启动start()方法启动

Thread和Runnable

class TestThread extends Thread{ public void run(){ for(int i=0;i<10;i++){ System.out.println(Thread.currentThread().getName()+"---is running"); } }}public class Thread01 { public static void main(String[] args) { TestThread tt1 = new TestThr

Android进阶——多线程系列之Thread、Runnable、Callable、Future、FutureTask

多线程系列之Thread.Runnable.Callable.Future.FutureTask 前言 多线程一直是初学者最抵触的东西,如果你想进阶的话,那必须闯过这道难关,特别是多线程中Thread.Runnable.Callable.Future.FutureTask这几个类往往是初学者容易搞混的.这里先总结这几个类特点和区别,让大家带着模糊印象来学习这篇文章 Thread.Runnable.Callable:都是线程 Thread特点:提供了线程等待.线程睡眠.线程礼让等操作 Runnab

Java 多线程(1)-Thread和Runnable

一提到Java多线程,首先想到的是Thread继承和Runnable的接口实现 Thread继承 public class MyThread extends Thread { public void run(){ int i = 0; System.out.println("--------------"+i++); } } Runnable接口实现 public class RunnableImpl implements Runnable { private long value =

Android中Handler 、Thread和Runnable之间的关系

在多线程编程的时候,我们经常会用到Handler,Thread和Runnable这三个类,我们来看看这三个类之间是怎么样的关系? 首先说明Android的CPU分配的最小单元是线程,Handler一般是在某个线程里创建的,因而Handler和Thread就是相互绑定的,一一对应. 而Runnable是一个接口,Thread是Runnable的子类.可以说,他俩都算一个进程. HandlerThread顾名思义就是可以处理消息循环的线程,他是一个拥有Looper的线程,可以处理消息循环. 与其说H

多线程-Thread,Runnable,Callable,Future,RunnableFuture,FutureTask

类图: 先看各自的源码: public interface Runnable { public abstract void run(); } public class Thread implements Runnable { /* What will be run. */ private Runnable target; } Thread与Runnable其实是一个装饰器模式. public interface Callable<V> { V call() throws Exception;

多线程-Thread与Runnable源码分析

Runnable: @FunctionalInterface public interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be call

带你玩转java多线程系列 二 Thread 和 Runnable

Thread 和 Runnable 1 Runnable是接口,而Thread是继承,可以同时实现多个接口,但是不能同时继承多个类 2 Runnable比Thread灵活的多 当我们使用Runnable测试多线程非常简单,因为Runnable是对Thread的进一步解耦 我们首先建立一个类记做为Model,实现Runnable接口,在类里建立一个实例变量,接着覆盖run方法. 我们重新建立一个含有main函数的类,在该类中我们首先建立一个Model类型的实例变量model,接着将该Runnabl