如何实现多线程

1.继承Thread类实现多继承(此法优缺点,若已经继承类,则无法再继承Thread类);

public class TestThread extends Thread {//自定义类继承Thread类
    //run()方法里是线程体
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(this.getName() + ":" + i);//getName()方法是返回线程名称
        }
    }
 
    public static void main(String[] args) {
        TestThread thread1 = new TestThread();//创建线程对象
        thread1.start();//启动线程
        TestThread thread2 = new TestThread();
        thread2.start();
    }
}


2.通过Runnable接口实现多继承

public class TestThread2 implements Runnable {//自定义类实现Runnable接口;
    //run()方法里是线程体;
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
    public static void main(String[] args) {
        //创建线程对象,把实现了Runnable接口的对象作为参数传入;
        Thread thread1 = new Thread(new TestThread2());
        thread1.start();//启动线程;
        Thread thread2 = new Thread(new TestThread2());
        thread2.start();
    }
}

步骤:先创建线程对象,然后启动线程对象


posted @ 2018-03-14 17:55  时光吹老了好男孩  阅读(283)  评论(0编辑  收藏  举报