1 线程构造方法
方法1:通过Runnable接口描述线程任务
public class RunnableThread implements Runnable {
public void run()
{
Long thread_id = Thread.currentThread().getId();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("this is RunnableThread, thread id = " + thread_id.toString() + '\n');
}
}
Long thread_id = Thread.currentThread().getId();
- 通过Thread类启动RunnableThread线程
public class MyThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
RunnableThread runnableThread = new RunnableThread();
Thread thread = new Thread(runnableThread);
thread.start();
System.out.print("main thread id is = " + Thread.currentThread().getId() + '\n');
thread.join();
}
}
public class MyThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
RunnableThread runnableThread = new RunnableThread();
ExecutorService exec_run = Executors.newCachedThreadPool();
for(int i = 0; i < 5; i++)
{
exec_run.execute(new RunnableThread());
}
exec_run.shutdown();
}
}
方法2:通过Callable接口创建可返回参数的任务
import java.util.concurrent.*;
import java.util.*;
public class CallableThread implements Callable<String> {
private int id;
public CallableThread(int id)
{
this.id = id;
}
public String call() throws InterruptedException {
long thread_id = Thread.currentThread().getId();
Thread.sleep(200);
return "result of RunnableThread " + id + " thread id = " + thread_id;
}
}
public class MyThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService exec_call = Executors.newCachedThreadPool();
ArrayList<Future<String>> futures = new ArrayList<Future<String>>();
for(int i = 0; i < 10; i++)
futures.add(exec_call.submit(new CallableThread(i)));
for(Future<String> fs : futures)
System.out.print(fs.get() + '\n');
}
}