首页 > 编程 > Java > 正文

java再复习——多线程之初识线程,并从源码角度分析start与run方法,Thread类与Runnable接口

2019-11-06 07:13:27
字体:
来源:转载
供稿:网友

进程与线程的概念。

进程:是操作系统为一个程序分配内存空间的基本单位。

线程:存在于一个进程里,是程序执行的基本单元。线程才是负责是去执行程序的。

java创建线程的方式:

一:继承Thread类,java为我们提供了封装好的线程类 Thread

class MyThread extends Thread{	@Override	public void run() {		System.out.PRintln("WTF?");	}}并且
	new MyThread().start();这样JVM就会起开启一个线程,然后去执行run()方法里面的代码。 注意只有是run方里面的代码才是线程执行的,并且得有JVM去调用,自己调用run方法不起租用。必须得调用start。

二:实现Runnable接口。

class MyRunnable implements Runnable{	public void run() {					}}扔给Thread类并调用start方法
		new Thread(new MyRunnable()).start();

切记,一定是扔给Thread的类,并且调用了start方法才会去开启一个线程并且执行run方法代码。

那么继承Thread类和实现Runnable接口方法有什么区别?

第一:java是单继承的,如果一个类继承了Thread类,那么这个类不能再继承任何类,我们知道什么时候才需要继承,在开发中,往往是有逻辑上和数据上的共同时才需要继承,而如果仅仅是要执行多线程的话就把继承这唯一的机会给使用了,那么后面的局限性太大了,所以java又提供了实现Runnable接口这一方式。

第二:其实Thread类是实现了Runnable接口的类,从接口和类上来分析这件事,不难理解,接口只是定义一个协议,就是run方法,java与我们协议,要在多线程中执行的代码放在run方法中,所以这就是Runnable接口的由来,那么到底该如何开启线程呢? 这就是Thread类,java实现了自己的Runnable接口并且封装了这个功能类,就叫Thread类。

所以在java中要想开启一个线程,必须是调用了Thread或者它子类的start方法,而run方法只是保存要在多线程中执行的代码的一个接口方法。

而且Thread类的run方法源码是这样的:

    @Override    public void run() {        if (target != null) {            target.run();        }    }而这个target就是Runnable对象。

并且Thread类的start方法源码是这样的:

    /**     * Causes this thread to begin execution; the Java Virtual Machine     * calls the <code>run</code> method of this thread.          //中文注释: 调用此方法这个线程就是开启是执行,JVM会调用线程的run方法。     * <p>     * The result is that two threads are running concurrently: the     * current thread (which returns from the call to the     * <code>start</code> method) and the other thread (which executes its     * <code>run</code> method).                                  //中文注释:结果是当前有两个线程在运行,一个是此线程,另一个是开启此线程的线程     * <p>     * It is never legal to start a thread more than once.     * In particular, a thread may not be restarted once it has completed     * execution.                                                 //中文注释:它从不会被启动多次,一个线程不可能在它还没完成之前被启动多次     *									      (注意,一个线程在没执行完之前如果被启动,会抛出非法状态异常)     * @exception  IllegalThreadStateException  if the thread was already     *               started.     * @see        #run()     * @see        #stop()     */    public synchronized void start() {        //...此方法的解释被我删除        group.add(this);        boolean started = false;        try {            start0();              started = true;        } finally {          ....        }    }	//本地方法,去调用该操作系统开启一个线程    private native void start0();


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表