欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java创建线程示例代码,java线程示例代码,在java中有两种方法可

来源: javaer 分享于  点击 28221 次 点评:113

java创建线程示例代码,java线程示例代码,在java中有两种方法可


在java中有两种方法可以创建线程,一种方法是从Thread类继承,实现Thread类的run方法,另一种方式是实现Runnable接口,然后将Runnable的对象作为参数给Thread实例。

如下是两种方法的实现代码示例:

从Thread类继承实现多线程:

public class MyThread extends Thread {    /**     * This method is executed when the start() method is called on the thread     * so here you will put the 'thread code'.     */    public void run() {        System.out.println("Thread executed!");    }    /**     * @param args the command line arguments     */    public static void main(String[] args) {        Thread thread = new MyThread();        thread.start();    }}

通过实现Runnable接口实现多线程:

public class MyRunnable implements Runnable {    /**     * As in the previous example this method is executed      * when the start() method is called on the thread     * so here you will put the 'thread code'.     */    public void run() {        System.out.println("Thread executed!");    }    /**     * @param args the command line arguments     */    public static void main(String[] args) {   //create a Thread object and pass it an object of type Runnable        Thread thread = new Thread(new MyRunnable());        thread.start();    }}
相关栏目:

用户点评