java 线程创建

继承 Thread 


public
class Demo1CreateThread{ public static void main(String[] args) throws InterruptedException { System.out.println("-----多线程创建开始-----"); // 1.创建一个线程 CreateThread createThread1 = new CreateThread(); CreateThread createThread2 = new CreateThread(); // 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法 System.out.println("-----多线程创建启动-----"); createThread1.start(); createThread2.start(); System.out.println("-----多线程创建结束-----"); } static class CreateThread extends Thread { public void run() { String name = Thread.currentThread().getName(); for (int i = 0; i < 5; i++) { System.out.println(name + "打印内容是:" + i); } } } }

实现 Runnable 

public class Demo2CreateRunnable {

    public static void main(String[] args) {
        System.out.println("-----多线程创建开始-----");
        // 1.创建线程
        CreateRunnable createRunnable = new CreateRunnable();
        Thread thread1 = new Thread(createRunnable);
        Thread thread2 = new Thread(createRunnable);
        // 2.开始执行线程 注意 开启线程不是调用run方法,而是start方法
        System.out.println("-----多线程创建启动-----");
        thread1.start();
        thread2.start();
        System.out.println("-----多线程创建结束-----");
    }

    static class CreateRunnable implements Runnable {

        public void run() {
            String name = Thread.currentThread().getName();
            for (int i = 0; i < 5; i++) {
                System.out.println(name + "的内容:" + i);
            }
        }
    }
}

匿名内部类

使用线程的内匿名内部类方式,可以方便的实现每个线程执行不同的线程任务操 作

public class Demo3Runnable {
    public static boolean exit = true;

    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            public void run() {
                String name = Thread.currentThread().getName();
                for (int i = 0; i < 5; i++) {
                    System.out.println(name + "执行内容:" + i);
                }
            }
        }).start();

        new Thread(new Runnable() {
            public void run() {
                String name = Thread.currentThread().getName();
                for (int i = 0; i < 5; i++) {
                    System.out.println(name + "执行内容:" + i);
                }
            }
        }).start();

        Thread.sleep(1000l);
    }
}

实现Runnable接口比继承Thread类所具有的优势:
1. 适合多个相同的程序代码的线程去共享同一个资源。

2. 可以避免java中的单继承的局限性。

3. 增加程序的健壮性,实现解耦操作,代码可以被多个线程共享,代码和数 据独立。
4. 线程池只能放入实现Runable或callable类线程,不能直接放入继承Thread 的类
原文地址:https://www.cnblogs.com/angdh/p/15564151.html