实现多线程的两种方式

实现Runnable接口线程

步骤:

  1. 实现Runnable接口
  2. 重写run()方法
  3. 实例化对象
  4. 调用start()方法
public class HelloRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("我是子线程:" + i);
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // 实例化子线程
        HelloRunnable helloRunnable = new HelloRunnable();
        Thread thread = new Thread(helloRunnable);
        thread.start();
        for (int i = 0; i < 10; i++) {
            System.out.println("我是主线程main:" + i);
        }
    }
}

实现Runnable接口线程改名

步骤:

  1. 实现Runnable接口
  2. 重写run()方法
  3. 实例化对象
  4. 调用start()方法
  5. 使用Thread.currentThread().setName()和Thread.currentThread().getName()
public class HelloRunnableName implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("子线程的名称:" + Thread.currentThread().getName() + ":" + i);
        }
    }

    /**
     * 主方法/主线程
     * @param args
     */
    public static void main(String[] args) {
        // 实例化子线程
        HelloRunnableName helloRunnableName = new HelloRunnableName();
        Thread thread = new Thread(helloRunnableName, "我是子线程1");
        thread.start();

        Thread.currentThread().setName("我是主线程main1");

        for (int i = 0; i < 10; i++) {
            System.out.println("主线程名称:" + Thread.currentThread().getName()+ ":" + i);
        }
    }
}

继承Thread类

步骤:

  1. 继承Thread类
  2. 重写run()方法
  3. 实例化对象
  4. 调用start()方法
public class HelloThread extends Thread {
    @Override
    public void run() {
        // super.run();
        for (int i = 0; i < 10; i++) {
            System.out.println("我是子线程:" + i);
        }
    }

    /**
     * 主方法/主线程
     * @param args
     */
    public static void main(String[] args) {
        HelloThread helloThread = new HelloThread();
        helloThread.start();

        for (int i = 0; i < 10; i++) {
            System.out.println("我是主线程main:"+i);
        }
    }
}

继承Thread类并改名

  1. 继承Thread类
  2. 重写run()方法
  3. 实例化对象
  4. 调用start()方法
  5. 使用Thread.currentThread().setName()和Thread.currentThread().getName()
public class HelloThreadName extends Thread {

    public HelloThreadName(String name) {
        super(name);
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("子线程名称:" + Thread.currentThread().getName() + ":" + i);
        }
    }

    /**
     * 主方法/主线程
     * @param args
     */
    public static void main(String[] args) {
        HelloThreadName helloThread = new HelloThreadName("我是子线程1");
        helloThread.start();

        Thread.currentThread().setName("我是主线程main1");

        for (int i = 0; i < 10; i++) {
            System.out.println("主线程名称:" + Thread.currentThread().getName() + ":"+i);
        }
    }
}

原文地址:https://www.cnblogs.com/godles/p/11926251.html