Java实现一个线程的两种方法

Java实现一个线程有两种方法:一种是继承父类Thread,重写其中的run()方法;另一种是实现接口Runnable接口,实现其中的run()方法

一、继承父类——Thread

直接上代码,代码之中解释了构造、创建、启动方法

import java.util.Date;

public class TestThread extends Thread {
    public int time;
    public String name;

    // 构造函数
    public TestThread(int time, String name) {
        this.time = time;
        this.name = name;
    }

    // 线程体函数
    @Override
    public void run() {
        while (true) {
            try {
                System.out.println(name + "阻塞" + time + " ms---_" + new Date());
                Thread.sleep(time);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TestThread thread1 = new TestThread(1000, "user1");
        TestThread thread2 = new TestThread(3000, "user2");
        thread1.start();
        thread2.start();
    }

}

二、实现接口——Runnable

依旧直接上代码,代码之中解释了构造、创建、启动方法

但是注意一点,Runable为非Thread子类的类提供了一种激活方式。通过实例化某个Thread实例并将自身作为运行目标,就可以实现Runnable的类而无需创建Thread的子类。

import java.util.Date;

public class TestRunnable implements Runnable {
    public int time;
    public String name;

    // 构建方法
    public TestRunnable(int time, String name) {
        this.name = name;
        this.time = time;
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println(name + "阻塞" + time + "me----" + new Date());
                Thread.sleep(time);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        TestRunnable unser1 = new TestRunnable(1000, "unser1");
        TestRunnable unser2 = new TestRunnable(3000, "unser2");
        // 直接调用run(),无需创建Thread()
        unser1.run();
        unser2.run();

        // 实例化一个Thread类
        // new Thread(unser1).start();
        // new Thread(unser2).start();

    }

}

 

这样就是我们创建java线程的两种方法

 

posted @ 2017-08-28 21:48  一木林森  阅读(262)  评论(0)    收藏  举报