java 开启子线程的三种方式

1. 实现多线程的方式

继承Thread类
实现Runnable接口
一般使用匿名的方式

2. 示例

package comi.example.liy.mytestdemo;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * Example local unit test, which will execute on the development machine (host).
 *
 * @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
 */
public class ExampleUnitTest {
    
    /**
     * 自定义线程类1:继承Thread类
     */
    class MyThread extends Thread{
        @Override
        public void run() {
            //super.run();
            for (int i = 0; i < 10; i++) {
                System.out.println("MyThread-"+i);
                //System.out.println(new Date()+"-"+i);
            }
        }
    }
    @Test
    public void test1(){
        MyThread myThread = new MyThread();
        myThread.start();
    }


    /**
     * 自定义线程类2:实现Runnable接口
     */
    class MyRunnable implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                System.out.println("MyRunnable-"+i);
            }
        }
    }
    @Test
    public void test2(){
        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();
    }
    

    /**
     * 一般使用匿名的方式(一个匿名对象:new Thread().start(),一个接口式的匿名内部类:new Runnable(){})
     */
    @Test
    public void test3(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    System.out.println("Thread_Runnable-"+i);
                }
            }
        }).start();
    }



}
posted @ 2023-02-01 20:20  鲸小鱼-  阅读(877)  评论(0编辑  收藏  举报