1、继承Thread类创建线程
public class ThreaDemo extends Thread{
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " run")
}
}
2、实现Runnable接口创建线程
public class RunnableDemo implements Runnable{
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " run")
}
public static void main(String[] args){
RunnableDemo runnableDemo = new RunnableDemo();
Thread thread = new Thread(RunnableDemo);
thread.start();
System.out.println(Thread.currentThread().getName() + " run")
}
}
3、使用Callable和Future创建线程
public class CallableDemo implements Callable<Integer>{
@Override
public Integer call(){
System.out.println(Thread.currentThread().getName() + " call")
return 0
}
}
public calss CallableTest{
public static void main(String[] args){
FutureTask<Integer> futureTask = new FutureTask(new CallableDemo());
Thread thread = new Thread(futureTask);
thread.start();
System.out.println("返回结果 " + futureTask.get());
System.out.println(Thread.currentThread().getName() + " main")
}
}
运行结果
Thread-0 call 返回结果 0 main main
4、使用线程池创建线程
使用Executor框架,提供四种线程池
1、newCachedThreadPool
- newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则创建线程。
2、newFixedThreadPool
- newFixedThreadPool创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
3、newScheduledThreadPool
- newScheduledThreadPool创建一个周期性线程池,支持定时及周期性任务执行。
4、newSingleThreadExecutor
- newSingleThreadExecutor创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序执行。
举例:newFixedThreadPool
public class ThreadDemo extend Thread{
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " 正在执行")
}
}
public class TestFixedThreadPool{
public static void main(String[] args){
ExecutorService pool = Executor.newFixedThreadPool(3);
Thread t1 = new ThreadDemo();
Thread t2 = new ThreadDemo();
Thread t3 = new ThreadDemo();
pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.shutdown();
}
}
|