1)继承Thread类的子类:
class FirstThread extends Thread{
@Override
public void run() {
System.err.println("first thread.");
}
}
new FirstThread().start();
2)实现Runnable接口
class SecondThread implements Runnable{
@Override
public void run() {
System.err.println("second thread.");
}
}
new Thread(new SecondThread()).start();
3)实现Callable接口来创建Thread线程
class ThreeCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
ThreeCallable threeCallable = new ThreeCallable();
FutureTask<Integer> ft = new FutureTask<Integer>(threeCallable);
new Thread(ft).start();
System.err.println("ft:"+ft.get());
4)利用线程池创建多线程的方式
Executors.newFixedThreadPool(3).execute(new Runnable() {
@Override
public void run() {
System.out.println("newFixedThreadPool_" + Thread.currentThread().getName());
}
});
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
System.out.println("newCachedThreadPool_" + Thread.currentThread().getName());
}
});
Executors.newScheduledThreadPool(3).execute(new Runnable() {
@Override
public void run() {
System.out.println("newScheduledThreadPool_" + Thread.currentThread().getName());
}
});
|