多线程——Runnable接口

曾经终败给现在 2023-08-17 16:09 197阅读 0赞

以实现Runable接口的方式创建线程比继承Thread类有很大的优越性,因为类不能多重继承,即一个类只能继承一个类,那么如果该类已经继承了一个类,就不能实现多线程了,但是可以通过实现Runable接口的方式实现多线程。

1、Runnable实现多线程

  1. package pers.zhb.runnable;
  2. public class MyThread implements Runnable{
  3. public void run() {
  4. for (int i = 0; i < 20; i++) {
  5. System.out.println(Thread.currentThread().getName()+":正在执行!"+i);
  6. }
  7. }
  8. }
  9. package pers.zhb.runnable;
  10. public class RunnableDemo {
  11. public static void main(String[] args) {
  12. MyThread mt=new MyThread();
  13. Thread t2=new Thread(mt);//Thread类本质上也是实现了Runnable接口,但是Run方法是空的
  14. t2.start();
  15. for (int i = 0; i < 20; i++) {
  16. System.out.println("主函数线程!"+i);
  17. }
  18. System.out.println("主函数执行结束了");
  19. }
  20. }

2、join()方法的使用

主线程在子线程运行结束后才开始运行。

  1. package pers.zhb.runnable;
  2. public class MyThread implements Runnable{
  3. public void run() {
  4. for (int i = 0; i < 20; i++) {
  5. System.out.println(Thread.currentThread().getName()+":正在执行!"+i);
  6. }
  7. }
  8. }
  9. package pers.zhb.runnable;
  10. public class RunnableDemo {
  11. public static void main(String[] args) throws InterruptedException {
  12. MyThread mt = new MyThread();
  13. Thread t1 = new Thread(mt);
  14. t1.start();
  15. t1.join();
  16. for (int i = 0; i < 20; i++) {
  17. System.out.println("主函数线程!" + i);
  18. }
  19. System.out.println("主函数执行结束了");
  20. }
  21. }

1392562-20190817200547099-1381898129.png

转载于:https://www.cnblogs.com/zhai1997/p/11370201.html

发表评论

表情:
评论列表 (有 0 条评论,197人围观)

还没有评论,来说两句吧...

相关阅读