Java创建线程的三种方式

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java创建线程的三种方式相关的知识,希望对你有一定的参考价值。

1.继承Runnable接口

package test;
class RunnableDemo implements Runnable{
    private Thread t;
    private String threadName;
    
    RunnableDemo(String name){
        threadName=name;
        System.out.println("Creating "+name);
    }
    public void run(){
        System.out.println("Running "+threadName);
        try{
            for(int i=4;i>0;i--){
                System.out.println("Thread: "+threadName+" "+i);
                Thread.sleep(50);
            }
        }
        catch(InterruptedException e){
            System.out.println("Thread "+threadName+" Excepted");
        }
        System.out.println("Thread "+threadName+" Exiting");
    }
    public void start(){
        System.out.println("Starting "+threadName);
        if(t==null){
            t=new Thread(this,threadName);
            t.start();
        }
    }
}
public class HelloWorld {
    public static void main(String []args) {
        RunnableDemo R1=new RunnableDemo("thread1");
        R1.start();
        RunnableDemo R2=new RunnableDemo("thread2");
        R2.start();
    }
}

2.继承Thread类

package test;
class ThreadDemo extends Thread{
    private Thread t;
    private String threadName;
    
    ThreadDemo(String name){
        threadName=name;
        System.out.println("Creating "+name);
    }
    public void run(){
        System.out.println("Running "+threadName);
        try{
            for(int i=4;i>0;i--){
                System.out.println("Thread: "+threadName+" "+i);
                Thread.sleep(50);
            }
        }
        catch(InterruptedException e){
            System.out.println("Thread "+threadName+" Excepted");
        }
        System.out.println("Thread "+threadName+" Exiting");
    }
    public void start(){
        System.out.println("Starting "+threadName);
        if(t==null){
            t=new Thread(this,threadName);
            t.start();
        }
    }
}
public class HelloWorld2 {
    public static void main(String []args) {
        ThreadDemo T1=new ThreadDemo("thread1");
        T1.start();
        ThreadDemo T2=new ThreadDemo("thread2");
        T2.start();
    }
}

3.通过 Callable 和 Future 创建线程

以上是关于Java创建线程的三种方式的主要内容,如果未能解决你的问题,请参考以下文章

java创建线程的三种方式

Java创建线程的三种主要方式

Java创建线程的三种主要方式

java创建线程的三种方式及其对照

java创建线程的三种方式及其对比

49多线程创建的三种方式之继承Thread类