Java多线程:多线程 Thread 类 中常用的方法的使用

Java多线程:多线程 Thread 类 中常用的方法的使用

在这里插入图片描述


每博一文案

日本有一位方丈曾在其寺庙的公告栏上写下一句标语: ”没有失败的人生才最失败。“
深以为然,不上高山,不知平地,不经大海,不懂宽阔的涵义,人生需要许多试错的机会,各种滋味需要亲自
尝过,才知酸甜苦辣,人有了经历,才会长阅历,有了阅历,才会逐渐成熟自如。
稻盛和夫曾说:”在富裕的现代生活中,我们很难让孩子历经艰辛。“正因为如此,我们才应该告诉他们塑造人格
最重要的是经历辛苦,而且我们必须让这种想法根植于理性之中。
不经一番寒彻骨,怎得梅花扑鼻香。你来时走过的每一步,都算数。哪怕是走了歪路,绕了远路,那些经过的风景,
偶然发现的新方向,浪费的时间。都会以你意想不到的方式,回馈与你。
这些或欢喜,或痛苦的经历,都将成为生命中不可复制的财富,助你奔向更美好的未来。
                                            ——————   一禅心灵庙语


该文章主要介绍:关于 Thread 类中的一些常用方法的 介绍使用

1. start( ) 介绍 与 使用

start( ) : 方法的作用是启动一个新线程,新线程会执行相应的run()方法并且对于同一个对象的线程,不可以调用 start()方法两次不然会报异常 (IllegalThreadStateException) 非法线程异常,仅仅只能调用一次start()方法。

在这里插入图片描述

Thread 类中的 start() 的源码:

public synchronized void start() {
    /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
    if (threadStatus != 0)
        throw new IllegalThreadStateException();

    /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented.
     */
    group.add(this);

    boolean started = false;
    try {
        start0();
        started = true;
    } finally {
        try {
            if (!started) {
                group.threadStartFailed(this);
            }
        } catch (Throwable ignore) {
            /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
        }
    }
}

同一个线程调用一次 start()方法没有问题如下:

package blogs.blog4;

/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());
        // 同一个线程对象,调用一次 start();
        thread.start();

        // main 主线程
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }
    }
}

在这里插入图片描述


同一个线程对象,调用 start()方法两次会报错:的异常 IllegalThreadStateException 非法线程状态异常。 如下

package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());
        // 同一个线程对象,调用一次 start();
        thread.start();
        // 同一个线程对象,调用两个 start();方法报错
        thread.start();  // 报错

        // main 主线程
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }
    }
}

在这里插入图片描述


可以创建两个线程,分别调用 start()方法

package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());
        // 同一个线程对象,调用一次 start();
        thread.start();
        // 创建第二个线程对象
        Thread thread2 = new Thread(new MyThread5());
        thread2.start();

        // main 主线程
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }
    }
}

在这里插入图片描述


2. run( ) 介绍 与 使用

run() : 就和普通的成员方法一样,可以被重复调用。单独调用**run()**的话,会在当前线程中执行run(),而并不会启动新线程!

Thread 中的 run ()方法其实重写 Runnable 中的 run()的抽象方法。

run(): 通常需要重写Thread()类/Runnable 中的抽象方法,将创建的线程要执行的操作声明在此方法中(线程实际要处理的事务)

Thread 中的run()方法的源码:


public class Thread implements Runnable {
    /* What will be run. */
    private Runnable target;


/**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
}

Runnable 接口的源码:


package java.lang;

/**
 * The <code>Runnable</code> 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 <code>run</code>.
 * <p>
 * This interface is designed to provide a common protocol for objects that
 * wish to execute code while they are active. For example,
 * <code>Runnable</code> is implemented by class <code>Thread</code>.
 * Being active simply means that a thread has been started and has not
 * yet been stopped.
 * <p>
 * In addition, <code>Runnable</code> provides the means for a class to be
 * active while not subclassing <code>Thread</code>. A class that implements
 * <code>Runnable</code> can run without subclassing <code>Thread</code>
 * by instantiating a <code>Thread</code> instance and passing itself in
 * as the target.  In most cases, the <code>Runnable</code> interface should
 * be used if you are only planning to override the <code>run()</code>
 * method and no other <code>Thread</code> methods.
 * This is important because classes should not be subclassed
 * unless the programmer intends on modifying or enhancing the fundamental
 * behavior of the class.
 *
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@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 called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}


直接调用 run() 方法并不会创建线程,仅仅只是一个方法之间的回调而已。

package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());

        // 直接调用 run()方法不会创建新的线程,仅仅只是方法之间的回调而已
        thread.run();

        // main 主线程
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }
    }
}

在这里插入图片描述


2.1 start() 和 直接调用 run()的区别说明

  1. start() 方法会创建一个新线程,并由这个新线程启动调用 run()方法。
  2. 直接调用 run( ) 方法,并不会创建一个新线程而是由当前线程调用 run()方法,而且可以多次调用 run() 。
  3. 对于 start() 方法,同一个线程对象仅仅只能调用一次,调用第二次会报 :IllegalThreadStateException 异常错误。

3. currentThread( ) 介绍 与 使用

currentThread() :是一个静态方法,作用:返回当前执行的线程的引用:类似于 this 这样的引用。

在这里插入图片描述

package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());

        // 直接调用 run()方法不会创建新的线程,仅仅只是方法之间的回调而已
        thread.start();

        // main 主线程
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread());  // // 返回当前执行的线程的引用
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread());   // 返回当前执行的线程的引用
            System.out.println(Thread.currentThread().getName() + "--->" + i);
        }
    }
}

在这里插入图片描述

4. getName( ) / setName( ) 介绍 与 使用

setName() :对象方法,设置线程的名称。

在这里插入图片描述

getName() :对象方法,获取到线程的名称

在这里插入图片描述

package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());

        // 直接调用 run()方法不会创建新的线程,仅仅只是方法之间的回调而已
        thread.start();
        thread.setName("分支线程");   // 设置线程名

        Thread.currentThread().setName("主线程");   // 设置主线程名,// 先通过Thread.currentThread()方法获取当前线程的引用

        // main 主线程
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName());
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName());
        }
    }
}

在这里插入图片描述


5. yield( ) 介绍 与 使用

yield() 静态方法,作用:释放当前cpu执行的线程的占有的时间片(进入就绪状态), 注意虽然释放了:但是下一次cpu可能执行的还是这个我们(刚刚释放掉的线程),原因是:这个刚刚释放的线程又抢到(获取的)cpu的执行权限了。注意:yield() 并不会释放手中占有的锁

在这里插入图片描述

package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());

        // 直接调用 run()方法不会创建新的线程,仅仅只是方法之间的回调而已
        thread.start();
        thread.setName("分支线程");   // 设置线程名

        Thread.currentThread().setName("主线程");   // 设置主线程名,先通过Thread.currentThread()方法获取当前线程的引用

        // main 主线程
        for(int i = 0; i < 10; i++) {
            Thread.yield();  // 释放当前线程占用的时间片,(进入就绪状态)
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            Thread.yield();  // 释放当前线程占用的时间片,(进入就绪状态)
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }
    }
}

在这里插入图片描述


6. sleep( ) 介绍 与 使用

sleep() 的作用是让当前线程休眠,即当前线程会从 “运行状态” 进入到 “休眠(阻塞)状态”。 sleep()会指定休眠时间,线程休眠的时间会 大于/等于 该休眠时间;在线程重新被唤醒时,它会由 "阻塞状态" 变成 “就绪状态”,从而 等待cpu的调度执行

sleep( long millis ) 中的的参数中的单位是:毫秒。注意还要处理一个异常。

在这里插入图片描述

Thread.sleep(1000 * 1);      // 休眠 1 秒
Thread.sleep(1000 * 60);      // 休眠 1 分钟
Thread.sleep(1000 * 60 * 60);     // 休眠 1 小时
Thread.sleep(1000 * 60 * 60 * 24);  // 休眠 一天
Thread.sleep(1000 * 60 * 60 * 24 * 365 );  // 休眠 1 年
package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());

        // 直接调用 run()方法不会创建新的线程,仅仅只是方法之间的回调而已
        thread.start();
        thread.setName("分支线程");   // 设置线程名

        Thread.currentThread().setName("主线程");   // 设置主线程名,先通过Thread.currentThread()方法获取当前线程的引用

        // main 主线程
        for(int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000 * 1 );  // 休眠 1 秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }

    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for(int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000 * 1 );  // 休眠 1 秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }
    }
}

在这里插入图片描述


注意的是 sleep() 是静态方法,与对象无关,所以休眠的是当前执行的线程,不是调用的sleep()方法的对象线程。

如下,休眠的是 main 的主线程。

public class ThreadTest5 {

    public static void main(String[] args) {
        // 创建匿名实现 Runnable 的实现类
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println(Thread.currentThread().getName() + "-->" + i);
                }
            }
        });

        thread.start();

        for (int i = 0; i < 10; i++) {
            try {
                Thread.sleep(1000 * 1);  // 休眠 1 秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }

    }
}

在这里插入图片描述


7. join( ) 介绍 与 使用

join() : 方法 作用是:让当前线程进入等待状态,不是对象调用 join()的对象线程进入等待状态,只有当调用 join()方法的对象线程执行完,当前等待状态的线程,才会往后执行。

在这里插入图片描述

如下:

当 main 主线程中的 for()循环中的 i == 5 的时候,main 主线程进入 等待状态 ,让调用 thread.join()的分支线程先执行完,main 主线程才可以从 等待状态 进入到 运行状态,继续执行 main 主线程后面的程序。

package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());

        // 直接调用 run()方法不会创建新的线程,仅仅只是方法之间的回调而已
        thread.start();
        thread.setName("分支线程");   // 设置线程名

        Thread.currentThread().setName("主线程");   // 设置主线程名,先通过Thread.currentThread()方法获取当前线程的引用

        // main 主线程
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);
            if (i == 5) {
                try {
                    thread.join();  // 当前线程停止,让 thread 分支线程执行完,再处理 Main 主线程中的程序
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }
    }
}

在这里插入图片描述


8. isAlive() 介绍 与 使用

isAlive() : 判断判断当前线程是否存活,如果存活 返回 true ,如果不存活,返回 false。

在这里插入图片描述


package blogs.blog4;


/**
 * Thread 类中常用的一些方法的介绍和使用
 */
public class ThreadTest5 {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyThread5());

        // 直接调用 run()方法不会创建新的线程,仅仅只是方法之间的回调而已
        thread.start();
        thread.setName("分支线程");   // 设置线程名

        Thread.currentThread().setName("主线程");   // 设置主线程名,先通过Thread.currentThread()方法获取当前线程的引用

        // main 主线程
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);
            // 判断当前线程是否存活。
            System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().isAlive());  //
            if (i == 5) {
                try {
                    thread.join();  // 当前线程停止,让 thread 分支线程执行完,再处理 Main 主线程中的程序
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(thread.getName() + "-->" + thread.isAlive());

            }

        }
    }
}


class MyThread5 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + "-->" + i);
        }
    }
}

在这里插入图片描述


9. 总结:

  1. start() : 启动当前线程,调用当前线程的run()方法,一个线程对象仅仅只能调用一次 start() 不然报:IllegalThreadStateException) 非法线程异常。
  2. run(): 通常需要重写Thread()类/Runnable 中的抽象方法,将创建的线程要执行的操作声明在此方法中(线程实际要处理的事务),直接调用 run()方法并不会创建新的线程,而是当前线程的简单的方法的调用,可以多次调用。
  3. currentThread():静态方法,返回当前执行的线程的引用
  4. .setName()设置线程名,getName()获取线程名:如果是设置主线程名的话,需要先获取到当前执行的线程的引用: Thread.currentThread()。因为main主线程没有继承 Thread 类,无法直接调用父类中的方法。
  5. yield() 静态方法,作用:释放当前cpu执行的线程的占有的时间片(进入就绪状态), 注意虽然释放了:但是下一次cpu可能执行的还是这个我们(刚刚释放掉的线程),原因是:这个刚刚释放的线程又抢到(获取的)cpu的执行权限了。注意:yield() 并不会释放手中占有的锁
  6. sleep() 的作用是让当前线程休眠,即当前线程会从 “运行状态” 进入到 “休眠(阻塞)状态”。 sleep()会指定休眠时间,线程休眠的时间会 大于/等于 该休眠时间;在线程重新被唤醒时,它会由 "阻塞状态" 变成 “就绪状态”,从而 等待cpu的调度执行 。sleep( long millis ) 中的的参数中的单位是:毫秒。注意还要处理一个异常。
  7. join() : 方法 作用是:让当前线程进入等待状态,不是对象调用 join()的对象线程进入等待状态,只有当调用 join()方法的对象线程执行完,当前等待状态的线程,才会往后执行。
  8. isAlive() : 判断判断当前线程是否存活,如果存活 返回 true ,如果不存活,返回 false。

10. 最后:

限于自身水平,其中存在的错误,希望大家给予指教,韩信点兵——多多益善,谢谢大家,后会有期,江湖再见 !!!

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值