JAVA 使用线程的几种方式

时间:2021-08-05 12:36:31

之前放在自己网站上的例子,因为网站关闭,已经找不到了,想用的时候,没有的话又重新翻书是很麻烦的事情。所以重新记录一下,以备将来查看。

第一种,让任务类继承Runable接口,然后将任务类对象放入Thread对象的构造器,通过Thread.start()方法执行调用。

package com.test.thread;

public class ThreadTest1 {
public static void main(String[] args) {
Thread thread = new Thread(new task(1));
thread.start();
    System.out.println("hello");
}
} class task implements Runnable { private final int taskid; public task(int taskid) {
this.taskid = taskid;
} public void run() {
System.out.println(this);
} @Override
public String toString() {
return "task [taskid=" + taskid + "]";
} }

执行结果:

hello
task [taskid=1]

第二种,就是第一种方式的改进,好处之一就是不用显示地创建Thread对象了,其他的好处还有,我不知道。这是JAVA SE5/6启动任务的优选方法。和方式一的区别,仅仅是main方法的区别:

ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new Task1(1));  

还有一种就是继承Thread类啦。并发编程太复杂了, 暂时写这么多把,以后用到的时候再说。