实现多线程的两种方式

继承Thread

public class Test1 extends Thread{
    String thread ;
    public Test1(String thread){
        this.thread = thread;
    }
    
    public void run(){
        System.out.println(thread+"正在执行");
    }
    public static void main(String args[]){
        new Test1("线程一").start();
        new Test1("线程二").start();
        new Test1("线程三").start();
        new Test1("线程四").start();
        new Test1("线程五").start();
        new Test1("线程六").start();
    }
}

实现Thread

public class TestRunnable implements Runnable{
    private String ThreadName ;
    
    public TestRunnable(String ThreadName){
        this.ThreadName = ThreadName;
    }
    @Override
    public void run() {
        System.out.println(ThreadName+"正在被执行");
    }
}

public class Test2{
    
    public static void main(String args[]){
        Thread thread1 = new Thread(new TestRunnable("线程一"));
        Thread thread2 = new Thread(new TestRunnable("线程二"));
        thread1.start();
        thread2.start();
    }
}

事实上Thread()类也是实现了Runnable()接口,这就是为什么我们在写run()方法,是重写的。

 

posted @ 2016-12-19 13:32  冰镇矿泉水  阅读(220)  评论(0编辑  收藏  举报