Java多线程:启动线程(三)

Java线程可以执行你写的程序,当你执行main()函数时,JVM会替你创建一个main线程来执行你的程序。
Java线程其实也是对象,我们可以在main()函数中创建一个Thread对象并启动它,这样当main线程在执行时,便会创建另一个线程。

如何创建并启动Java线程

public class JavaThreadTest {
    public static void main(String[] args) {
        Thread t = new Thread();
        t.start();
    }
}

当我们创建一个Thread对象并调用它的start()方法时,我们便启动了一个线程。但是上面这个例子中,我们没有指定这个新的线程需要执行的代码,因此在启动后,这个线程便会马上停止。
如何指定线程需要执行的代码,一般来说有两种方法:

继承Thread

继承Thread,并重写它的run()方法,在run方法中指定要执行的代码。

public class JavaThreadTest {
    public static void main(String[] args) {
        Thread t = new MyThread();
        t.start();
        System.out.println("main thread");
    }
}

class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("new thread");
    }
}

实现Runnable

实现Runnable接口,实现它的run()方法,并将Runnable对象作为参数传给Thread的构造器。

public class JavaThreadTest {
    public static void main(String[] args) {
        Thread t = new Thread(new MyRunnable());
        t.start();
        System.out.println("main thread");
    }
}

class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("runnable thread");
    }
}

暂停线程

通过调用Thread.sleep(),可以让线程暂停。

try {
    Thread.sleep(10L * 1000L); //暂停10秒
} catch (InterruptedException e) {
    e.printStackTrace();
}

停止线程

虽说Thread有提供stop()方法来停止线程,但是stop()方法并不提供任何保证,也就是当你停止线程的时候,我们并不知道线程所操作的对象的状态时怎么样的,这可能会引发许多意想不到的问题。
但我们可以自己给Runnable提供一个新的doStop方法,来实现停止线程。

public class StopThread {
    public static void main(String[] args) {
        CanStopRunnable r = new CanStopRunnable();
        Thread t = new Thread(r);
        t.start();
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        r.doStop();
    }
}

class CanStopRunnable implements Runnable {
    private boolean isStop = false;

    @Override
    public void run() {
        while (keepRunning()) {
            System.out.println("running...");
        }
    }

    public boolean keepRunning() {
        return !isStop;
    }

    public synchronized void doStop() {
        this.isStop = true;
        System.out.println("stop!");
    }
}

参考:http://tutorials.jenkov.com/java-concurrency/creating-and-starting-threads.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值