线程的创建方式及start和run的区别

public class Test {

public static void main(String[] args) {
    MyThread myThread = new MyThread();
    myThread.start();


    MyThread2 myThread2 = new MyThread2();
    Thread thread = new Thread(myThread2);
    thread.start();

}




}

class MyThread extends Thread{
    public void run(){
        System.out.println("这是继承线程类创建的。。。");
    }
}

class MyThread2 implements Runnable{
    public void run(){
        System.out.println("这是实现Runnable接口创建的。。。");
    }
}

一共有两种方式创建多线程。

 

下面再给一个例子:

public class Test {

    public static void main(String[] args) {
        Thread t = new Thread() {
            @Override
            public void run() {
                pong();
            }
        };
        //执行start方法,实现真正的多线程的效果
        t.start();
        int count = 0;
        for (int i = 0; i < 1000000; i++) {
            count += i;
        }
        System.out.println(count);
        System.out.println("ping");


    }

    static void pong() {
        System.out.println("pong");
    }
}

 

public class Test {

    public static void main(String[] args) {
        Thread t = new Thread() {
            @Override
            public void run() {
                pong();
            }
        };
        //直接执行run方法,还是单线程状态,打印结果一直是pong ping
        t.run();
//        int count = 0;
//        for (int i = 0; i < 1000000; i++) {
//            count += i;
//        }
//        System.out.println(count);
        System.out.println("ping");


    }

    static void pong() {
        System.out.println("pong");
    }
}

 

©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页