多线程爬坑记--基础篇(一)

来源:互联网 发布:国产胖熊熊片数据库 编辑:程序博客网 时间:2024/06/08 18:41

本篇根据> http://www.importnew.com/21136.html学习整理。

package main;/** * 多线程实现方式1: * 实现Runnable接口,实现run方法 */public class 多线程_实现Runnable接口 implements Runnable {    public 多线程_实现Runnable接口() {    }    @Override    public void run() {        System.out.println("子线程ID:"+Thread.currentThread().getId());    }}
package main;/** * 多线程实现方式2: * 继承Thread类,重写run()方法. */public class 多线程_继承Threadextends Thread {    private String name;    public 多线程_继承Thread类(String name) {        this.name = name;    }    @Override    public void run() {        System.out.println("name:" + name + "子线程ID:" + Thread.currentThread().getId());    }}
package test;import main.多线程_实现Runnable接口;import main.多线程_继承Thread类;import org.junit.jupiter.api.Test;public class 测试多线程 {    @Test    public void test1() {        System.out.println("主线程ID:" + Thread.currentThread().getId());        多线程_继承Thread类 thread1 = new 多线程_继承Thread类("startThread1");        thread1.start();        多线程_继承Thread类 thread2 = new 多线程_继承Thread类("runThread2");        thread2.run();    }    /**     * 运行结果:         主线程ID:1         name:runThread2子线程ID:1         name:startThread1子线程ID:12     */    /**     * #分析     * 1,main方法实际上就是一个主线程     * 2,线程通过start()方法启动,如果直接调用run()方法,作用和普通方法一样.     * 3,新线程创建的过程不会阻塞主线程的后续执行.     */    @Test    public void test2() {        System.out.println("主线程ID:" + Thread.currentThread().getId());        多线程_实现Runnable接口 runnable = new 多线程_实现Runnable接口();        Thread thread = new Thread(runnable);        thread.start();    }    /**     * 运行结果:         主线程ID:1         子线程ID:12     */    /**#     * 解析     *  需要将runnable作为参数传递到Thread中,在通过Thread的start()方法,启动线程     *  如果直接调用run()和普通方法无异.     */    /**     * 总结:     *  第一种:     *   1,继承Thread类,重写run()方法.     *   2,通过thread.start()启动线程.     *     *  第二种:     *   1,实现Runnable接口,重写run()方法.     *   2,创建Thread对象,将Runnable作为参数传递过来.     *   3,thread.start()启动线程.     */    /**相同点:     * 1,都需要run()方法,     * 2,都需要通过Thread的start()方法启动线程     */}