1.业务类实现Runnable接口
2.Thread类注入业务类并启动
代码如下:
public class RunnableDemo { public static void main(String[] args) { //Thread构造器注入实现类并启动 new Thread(new RunnableWorker()).start(); } } //实现Runnable接口 class RunnableWorker implements Runnable { public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); } } } 复制代码
业务类继承Thread,可直接以线程方式运行。代码如下:
public class ThreadDemo extends Thread { public static void main(String[] args) { new ThreadDemo().start(); } @Override public void run() { for (int i = 0; i < 10; i++) { System.out.println(i); } } } 复制代码
业务类可以实现Callable接口或者Runnable接口,二者的区别是Callable执行完后有返回值,Runnable没有返回值。
代码如下:
public class FutureDemo { public static void main(String[] args) { FutureTask<Integer> task = new FutureTask(new CallableWorker()); new Thread(task).start(); try { System.out.println(task.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } } class CallableWorker implements Callable<Integer> { public Integer call() throws Exception { return 10; } } 复制代码
业务类可以实现Callable接口或者Runnable接口,二者的区别是Callable执行完后有返回值,Runnable没有返回值。
代码如下:
public class ExecutorsDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建线程池 ExecutorService executorService = Executors.newFixedThreadPool(1); //提交匿名Callable Future<Integer> future = executorService.submit(new Callable<Integer>() { public Integer call() throws Exception { return 10; } }); //获取线程执行返回值 System.out.println(future.get()); } } 复制代码
end.
站点: javashizhan.com/
微信公众号: