创建一个线程可以通过两种方法:

继承 Thread 类,并override run() 方法
实现 Runnable 接口,并override run() 方法
现在给定一下代码:

import java.util.*;
import java.io.*;
import java.lang.*;

public class Demo extends Thread{

    public static void main(String[] args) {
        Runner1 runner1 = new Runner1();
        Runner2 runner2 = new Runner2();
        Thread thread1 = new Thread(runner1);
        Thread thread2 = new Thread(runner2);
        thread1.start();
        thread2.start();
        // thread1.run();
        // thread2.run();
    }
    
}
 
class Runner1 implements Runnable { // 实现了Runnable接口,jdk就知道这个类是一个线程
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("进入Runner1运行状态——————————" + i);
        }
    }
}
 
class Runner2 implements Runnable { 
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("进入Runner2运行状态==========" + i);
        }
    }
}

当创建两个 Thread 实例之后,调用 run() 打印的结果如下:

QQ截图20191111104800.png

可以发现依然是按顺序执行指令,并未多线程交替执行。

但当调用 start() 方法后,print结果为:

1.png

此时两个线程可以交替执行

事实上, run() 在我们人为调用的时候,仅仅是一个普通方法,顺序执行是显然的,而在我们调用 start() 时,才是真正开启了一个线程,可以看看文档中对于 start() 的说明:

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

start() 一旦被调用,是由 JVM 调用 run() ,此时可以使两个线程同时运行。

注意:

不能调用同一线程超过一次,且当一个线程执行后可能不能再次启动。


最后,补充多线程使用时的注意事项:

有效利用多线程的关键是理解程序是并发执行而不是串行执行的。例如:程序中有两个子系统需要并发执行,这时候就需要利用多线程编程。
通过对多线程的使用,可以编写出非常高效的程序。不过请注意,如果你创建太多的线程,程序执行的效率实际上是降低了,而不是提升了。
请记住,上下文的切换开销也很重要,如果你创建了太多的线程,CPU 花费在上下文的切换的时间将多于执行程序的时间!


JmsAllen
1 声望1 粉丝

少玩游戏,多写bug