Java多线程应注意的细节之一

时间:2021-07-30 17:38:55
我们知道在Java中有两种方式可以实现Java的多线程,一种是通过继续Thread类并重写run()方法;另一种是通过实现Runnable接口。废话少说,先跑下面的例子先:

package com.kkoolerter.thread;

public class ThreadTest {

   
    public static void main(String[] args) {
        new ThreadA("threadA").start();
        new Thread(new RunnableA("runnable")).start();
        new RunnableA("runnableA").run();
        new RunnableA("runnableB").run();
        new ThreadA("threadB").run();
        new ThreadA("threadC").run();
        System.out.println("[threadC] finished executing.");
    }

}

class ThreadA extends Thread{

    public ThreadA(String name){
        this.setName(name);
    }
    public ThreadA(Runnable runnable){
        super(runnable);
    }
    @Override
    public void run() {
        System.out.println("Thread:["+this.getName()+"]begine");
        System.out.println(this.getName()+" current thread is:["+Thread.currentThread().getName()+"]");
        for(long i = 0;i<9999999;i++);
        System.out.println("Thread:["+this.getName()+"]end\n");
    }
   
}

class RunnableA implements Runnable{
    private String name;
    public RunnableA(String name){
        this.name = name;
    }
    @Override
    public void run() {
        System.out.println("Thread:["+this.name+"]begine");
        System.out.println(this.name+" current thread is:["+Thread.currentThread().getName()+"]");
        for(long i = 0;i<9999999;i++);
        System.out.println("Thread:["+this.name+"]end\n");
    }
   
}

上述例子可能的一个输出结果:

Thread:[threadA]begine
threadA current thread is:[threadA]
Thread:[runnableA]begine
runnableA current thread is:[main]
Thread:[threadA]end

Thread:[runnable]begine
runnable current thread is:[Thread-1]
Thread:[runnableA]end

Thread:[runnableB]begine
runnableB current thread is:[main]
Thread:[runnable]end

Thread:[runnableB]end

Thread:[threadB]begine
threadB current thread is:[main]
Thread:[threadB]end

Thread:[threadC]begine
threadC current thread is:[main]
Thread:[threadC]end

[threadC] finished executing.

从运行的结果可以知道,如果直接调用Thread或Runnable接口实现类的run()方法,那么它将在main方法线程里按顺序运行,相当于在main()方法里调用一个普通方法。所以在实现多线程时,应该调用Thread的start()方法,因为调用start()方法使该线程开始执行;Java 虚拟机调用该线程的 run 方法。结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。 注意:多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。

本文出自 “有思想的代码” 博客,请务必保留此出处http://wujuxiang.blog.51cto.com/2250829/427205