Java Thread中start()和run()方法的区别

1、run()
Thread的run()方法来自于Runnable接口,Thread的子类应该重写该方法,调用run()方法,只是相当于调用一个类中的一个普通方法,会在本线程中执行run()的方法体,不会开启另外一个线程!

2、start()
执行Thread的start()方法,会开启一个新的线程,在新的线程里面执行run()方法。
(If you directly call run() method, you are not using multi-threading feature since run() method is executed as part of caller thread.

If you call start() method on Thread, the Java Virtual Machine will call run() method and two threads will run concurrently - Current Thread (main() in your example) and Other Thread (Runnable r1 in your example).)

Example

public class PingPong {
    public static synchronized void main(String args[]) {
        Thread t = new Thread() {
            public void run() {
                pong();
            }
        };
        t.start();
        System.out.print("Ping");
    }

    static synchronized void pong() {
        System.out.print("Pong");
    }
}

输出:PingPong。因为主线程先获取到PingPong.class的管程锁,所以线程t必须等待主线程结束释放锁,才能执行pong()方法。

public class PingPong {
    public static synchronized void main(String args[]) {
        Thread t = new Thread() {
            public void run() {
                pong();
            }
        };
        //t.start();
        t.run();
        System.out.print("Ping");
    }

    static synchronized void pong() {
        System.out.print("Pong");
    }
}

输出:PongPing。执行t的run()方法只是简单的方法调用,直接在主线程执行pong()方法,pong()方法执行完之后顺序执行。

示例以及代码来自于《Java解惑》谜题76-乒乓。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值