前言,三种使用线程的方法:实现Runnable接口、实现Callable接口、继承Thread类。实现接口会更好,因为继承了Thread类就无法继承其他类,但可以实现多个接口
/**
* 线程状态:new、runnable、blocked、time waiting、waiting、terminated
* 类可能只要求可执行就行,继承整个Thread类开销过大
*/
一、实现Runnable接口
// 线程使用方式:实现Runnable接口,需要实现run()方法,通过Thread调用start()来启动线程 class MyRunnable implements Runnable { @Override public void run() { m1(); } public void m1(){ System.out.println("do something"); } public static void main(String[] args) { MyRunnable instance = new MyRunnable(); Thread thread = new Thread(instance); thread.start(); } }
二、实现Callable接口
// 线程使用方式:实现Callable接口,与Runnable相比,Callable可以有返回值,返回值通过FutureTask封装 class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { return m1(); } public Integer m1(){ return 123; } public static void main(String[] args) throws ExecutionException, InterruptedException { MyCallable myCallable = new MyCallable(); FutureTask<Integer> futureTask = new FutureTask<>(myCallable); Thread thread = new Thread(futureTask); thread.start(); System.out.println(futureTask.get()); } }
三、继承Thread类:
继承Thread类,同样也是需要实现run方法,因为Thread类也实现了Runnable接口;
当调用start()方法启动一个线程时,虚拟机会将该线程放入就绪队列等待调度,当一个线程被调度时就会执行该线程的start()方法
class MyThread extends Thread{ public void run(){ System.out.println("do something"); } public static void main(String[] args) { Thread thread = new MyThread(); thread.start(); } }
标签:java,方式,Thread,接口,start,线程,new,public From: https://www.cnblogs.com/jinziguang/p/17235666.html