1.通过继承thread类,重新run方法,调用start方法开启线程
public class MyThread extends Thread { @Override public void run() { System.out.println("run......"); } public static void main(String[] args) { MyThread t1 = new MyThread(); MyThread t2 = new MyThread(); t1.start(); t2.start(); } }
2.通过实现接口runnable
public class MyRunable implements Runnable {
public void run() {
System.out.println("RUNNABLE RUN...");
}
public static void main(String[] args) {
MyRunable r = new MyRunable();
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
3.通过实现接口callable
public class MyCallable implements Callable<String>{
public String call() throws Exception {
System.out.println(Thread.currentThread().getName());
return "OK";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable c = new MyCallable();
FutureTask <String> ft = new FutureTask<String>(c);
Thread t1 = new Thread(ft);
t1.start();
String result = ft.get();
System.out.println(result);
}
}
4.通过线程池创建线程,也是实现runable
public class MyExecutors implements Runnable { public void run() { System.out.printf("MyExecutors is run..."); } public static void main(String[] args) { ExecutorService threadPool = Executors.newFixedThreadPool(3); threadPool.submit(new MyExecutors()); //关闭线程池 threadPool.shutdown(); } }
runnable 与callable的区别
1.runnable调用run方法是没有返回值的
2.callable 调用call方法是有返回值的,是个泛型,和Future,FutureTask配合使用可以用来获取异步执行的结果
3.callable接口的call方法允许抛出异常,而runnable接口的run方法的异常只能内部消化,不能继续上抛