Java -- Create a new thread

Here is a simple procedure for running a task in a separate thread:

1. Place the code for the task into the "run" method of a class that implements the "Runnable" interface. That interface is very simple, with a single method:

public interface Runnable {
    void run();
}

Since "Runnable" is a functional interface, you can make an instance with a lambda expression:

Runnable r = () -> { task code };

2. Construct a "Thread" object from the "Runnable":

Thread t = new Thread(r);

3. Start the thread:

t.start();

NOTE:

You can also define a thread by forming a subclass of the "Thread" class, like this:

class MyThread extends Thread {
    public void rund() {
        task code
    }
}

Then you construct an object of the subclass and call its "start" method. However, this approach is no longer recommended. You decouple the task that is to be run in parrallel from the mechanism of running it. If you have many tasks, it is too expensive to create a separate thread for each of them. Instead, you can use a thread pool. 

CAUTION: Do not call the "run" method of the "Thread" class or the "Runnable" object. Calling the "run" method directly merely executes the task in the same thread -- no new thread is started. Instead, call the "Thread.start" method. It create a new thread that executes the "run" method.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值