继承Thread类(真正意义上的线程类)是Runnabel接口的实现
public class SimpleThread extends Thread {
private int countDown = 5;
private static int threadCount = 0;
public SimpleThread() {
super(Integer.toString(++threadCount));
start();
}
public String toString() {
return "#" + getName() + "(" + countDown + ").";
}
public void run() {
while(true) {
System.out.println(this);
if(-- countDown == 0)
return;
}
}
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
new SimpleThread();
}
}
}
实现Runnable接口,并重写里面的run方法
//Liftoff.java
public class LiftOff implements Runnable {
protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount ++;
public LiftOff() {
}
public LiftOff(int countDown) {
this.countDown = countDown;
}
public String status() {
return "#" + id + "(" + (countDown >0 ? countDown: "LiftOff") + ").";
}
@Override
public void run() {
// TODO Auto-generated method stub
while(countDown -- > 0) {
System.out.println(status());
Thread.yield();
}
}
}
//MoreBasicThreads.java
public class MoreBasicThreads {
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
new Thread(new LiftOff()).start();
}
System.out.println("Waiting for LiftOff");
}
}
实现Callable接口,重写call方法
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableDemo {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for(int i = 0; i < 10; i++) {
results.add(exec.submit(new TaskWithResult(i)));
}
for(Future<String> fs : results) {
try {
System.out.println(fs.get());
}catch(InterruptedException e) {
System.out.println(e);
}catch(ExecutionException s) {
System.out.println(s);
}finally {
exec.shutdown();
}
}
}
}
使用Executor框架创建线程池
//CachedThreadPool将为每个任务都创建一个线程
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CachedThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 5; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
//FixedThreadPool使用了有限的线程集来执行所提交的任务
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FixedThreadPool {
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(5);
for(int i = 0; i < 5; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
//SingleThreadExecutor就像是线程数量为1的FixedThreadPool
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Executors;
public class SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for(int i = 0; i < 5; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}