经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Java » 查看文章
Java多线程——之一创建线程的四种方法 - sun-sailing
来源:cnblogs  作者:sun-sailing  时间:2018/10/16 9:40:31  对本文有异议

1.实现Runnable接口,重载run()

  1. public class ThreadRunnable implements Runnable {
  2. public void run() {
  3. for (int i = 0; i < 10; i++) {
  4. System.out.println(Thread.currentThread() + ":" + i);
  5. }
  6. }
  7. }
  8.  
  9. public class ThreadMain {
  10. public static void main(String[] args)
  11. {
  12. ThreadRunnable threadRunnable = new ThreadRunnable();
  13. threadRunnable.run();
  14. }
  15. }

  

2.继承Thread类,复写run()

使用时通过调用Thread的start()(该方法是native),再执行创建线程的run()

不足:由于java为单继承,若使用线程类已经有个父类,则不能使用该方式创建线程。

  1. public class ThreadEx extends Thread {
  2. public void run() {
  3. for (int i = 0; i < 10; i++) {
  4. System.out.println(Thread.currentThread() + ":" + i);
  5. }
  6. }
  7. }
  8.  
  9.  
  10. public class ThreadMain {
  11. public static void main(String[] args)
  12. {
  13. ThreadEx threadEx = new ThreadEx();
  14. threadEx.start();
  15. }
  16. }

  

3.实现Callable接口,有返回值

补充:与实现Runnable接口类似,都是实现接口,不同的是该方式有返回值。

  1. import java.util.concurrent.Callable;
  2.  
  3. public class ThreadCallable implements Callable {
  4. public Object call() throws Exception {
  5. for (int i = 0; i < 10; i++) {
  6. System.out.println(Thread.currentThread() + ":" + i);
  7. }
  8. return "succeed";
  9. }
  10. }
  11.  
  12.  
  13. public class ThreadMain {
  14. public static void main(String[] args) throws Exception
  15. {
  16. ThreadCallable threadCallable = new ThreadCallable();
  17. System.out.println(threadCallable.call());
  18. }
  19. }

  

4.使用Executors创建ExecutorService,入参Callable或Future

补充:适用于并发

 

 

未完待续,补充源码

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号