目录
1、继承Thread类
public class ThreadTest extends Thread {
public void run() {
System.out.println("ThreadTest ... run()");
}
public static void main(String[] args) {
ThreadTest t1 = new ThreadTest() ;
ThreadTest t2 = new ThreadTest() ;
t1.start();
t2.start();
}
}
最直接的方式,简单地创建和运行线程。
2、实现Runnable接口
public class RunnableTest implements Runnable {
public void run() {
System.out.println("RunnableTest ... run()");
}
public static void main(String[] args) {
RunnableTest rt = new RunnableTest() ;
Thread t1 = new Thread(rt);
Thread t2 = new Thread(rt);
t1.start();
t2.start();
}
}
由于Java单继承的规则,一个类只能继承一个父类(如果一个类已经继承了其他类,就无法再继承 Thread 类)
接口提供了更好的灵活性和扩展性。一个类可以实现多个接口,从而具备多种能力。
3、实现Callable接口
public class CallableTest implements Callable<String> {
public String call() throws Exception {
System.out.println("CallableTest...call...");
return "OK";
}
public static void main(String[] args) throws Exception {
CallableTest ct = new CallableTest();
FutureTask<String> ft1 = new FutureTask<>(ct);
FutureTask<String> ft2 = new FutureTask<>(ct);
Thread t1 = new Thread(ft1);
Thread t2 = new Thread(ft2);
t1.start();
t2.start();
String result1 = ft1.get();
String result2 = ft2.get();
System.out.println("Result1: " + result1);
System.out.println("Result2: " + result2);
}
}
Callable接口与Runnable接口类似,但它可以返回结果,也可抛出异常。(通常与FutureTask一起使用,来获取线程执行的结果。)
4、使用线程池
public class ExecutorsTest implements Runnable{
@Override
public void run() {
System.out.println("ExecutorsTest...run...");
}
public static void main(String[] args) {
// 创建线程池对象
ExecutorService threadPool = Executors.newFixedThreadPool(3);
//提交线程
threadPool.submit(new ExecutorsTest());
threadPool.submit(new ExecutorsTest());
// 关闭线程池
threadPool.shutdown();
}
}
使用线程池可以减少线程创建和销毁的开销,也能更好地控制并发级别。线程池可以提供更好的性能和可扩展性。