java多线程
2015-07-17 18:47
423 查看
Thread创建的两种方式
实现runnable接口,实现run()方法继承Thread类
ExecutorService类,Callable接口和Future对象
上面两种方式执行完任务是没有返回值的,如果想要任务返回值,需要实现callable接口中的call()方法,利用线程池执行时返回Future对象import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadTest { /** * @param args * @throws ExecutionException * @throws InterruptedException */ @SuppressWarnings("unchecked") public static void main(String[] args) throws InterruptedException, ExecutionException { // TODO Auto-generated method stub ExecutorService pool=Executors.newFixedThreadPool(2); ThreadTest test=new ThreadTest(); pool.execute(test.new runnable()); pool.execute(test.new thread());//execute()参数只能是Runnable Future result=pool.submit(test.new callable());//submit()参数可以是Runnable,Callable System.out.println(result.get().toString()); pool.shutdown(); } class runnable implements Runnable { @Override public void run() { // TODO Auto-generated method stub System.out.println("thread created by implements runnnable"); } } class callable implements Callable { @Override public Object call() throws Exception { // TODO Auto-generated method stub System.out.println("task created by implements callable"); return "return value from callable"; } } class thread extends Thread { public void run() { System.out.println("thread created by extending Thread"); } } }
相关文章推荐
- Python3写爬虫(四)多线程实现数据爬取
- C#实现多线程的同步方法实例分析
- 浅谈chuck-lua中的多线程
- C#简单多线程同步和优先权用法实例
- C#多线程学习之(四)使用线程池进行多线程的自动管理
- C#多线程编程中的锁系统(三)
- C#多线程学习之(六)互斥对象用法实例
- 基于一个应用程序多线程误用的分析详解
- C#多线程学习之(三)生产者和消费者用法分析
- C#多线程学习之(一)多线程的相关概念分析
- C#多线程之Thread中Thread.IsAlive属性用法分析
- C#控制台下测试多线程的方法
- Ruby 多线程的潜力和弱点分析
- C#中WPF使用多线程调用窗体组件的方法
- C#实现多线程的Web代理服务器实例
- c#实现多线程局域网聊天系统
- PHP使用CURL实现多线程抓取网页
- 浅解关于C#多线程的介绍
- 批处理程序中的“多线程”处理代码
- c#中多线程访问winform控件的若干问题小结