Java多线程-创建启动线程

参考

http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

http://lavasoft.blog.51cto.com/62575/99151

 

创建线程

创建线程有两种方式

1、实现Runnable接口

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}

2、继承Thread类

public class HelloThread extends Thread {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new HelloThread()).start();
    }

}

 

侧重于选择第一种方式,实现Runnable接口更灵活,因为它还可以作为其它类的子类;此外把需要多线程执行的任务与线程管理分开是一个更好的设计

创建线程时建议指定名字,这样非常易于遇到问题时进行调试

 

启动线程

启动线程调用Thread.start方法

 

posted on 2014-11-05 17:12  ukouryou  阅读(84)  评论(0编辑  收藏  举报

导航