Java创建多线程的方法

多线程

​ Java 给多线程编程提供了内置的支持。 一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务。

多线程同一个时刻,可以执行多个线程,比如:一个qq进程,可以同时打开多个聊天窗口;一个迅雷进程,可以同时下载多个文件。

​ 在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。

代码实现方法

​ 下面使用两种方式打印10次hello,并输出线程名。

继承Thread的实现方式

public class Main {
    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        threadTest.start();
    }
}

class ThreadTest extends Thread{
    int count = 0;
    @Override
    public void run(){
        while (true) {
            count++;
            System.out.println("hello " + count + " threadName:" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 10) {
                break;
            }
        }
    }
}

运行结果

hello 1 threadName:Thread-0
hello 2 threadName:Thread-0
hello 3 threadName:Thread-0
hello 4 threadName:Thread-0
hello 5 threadName:Thread-0
hello 6 threadName:Thread-0
hello 7 threadName:Thread-0
hello 8 threadName:Thread-0
hello 9 threadName:Thread-0
hello 10 threadName:Thread-0

实现Runable接口的实现方式

注意:在这里不能直接调用run()方法

public class Main {
    public static void main(String[] args) {
        ThreadTest threadTest = new ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
    }
}

class ThreadTest implements Runnable{
    int count = 0;
    @Override
    public void run() {
        while (true) {
            count++;
            System.out.println("hello " + count + " threadName:" + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count == 10) {
                break;
            }
        }
    }
}

运行结果

hello 1 threadName:Thread-0
hello 2 threadName:Thread-0
hello 3 threadName:Thread-0
hello 4 threadName:Thread-0
hello 5 threadName:Thread-0
hello 6 threadName:Thread-0
hello 7 threadName:Thread-0
hello 8 threadName:Thread-0
hello 9 threadName:Thread-0
hello 10 threadName:Thread-0
原文地址:https://www.cnblogs.com/ilyar1015/p/14687661.html