java实现多线程有两种方法:1、集成Thread类、2、实现Runnable接口

时间:2021-05-14 17:31:14

实现Runnable接口有如下优势

1、避免由于java的单继承而带来的局限。

2、相同功能的线程可以共享同一个资源。

例如:

classMyThread extendsThread {

         privateinttickets = 5;

         publicvoidrun() {

                   for(inti = 0; i < 10; i++) {

                            if (tickets> 0) {

                                     System.out.println("Nowtickets is: " + tickets--);

                            }

                   }

         }

}

classMyThread2 implementsRunnable {

         privateinttickets = 5;

         publicvoidrun() {

                   for(inti = 0; i < 10; i++) {

                            if (tickets> 0) {

                                     System.out.println("Nowtickets is: " + tickets--);

                            }

                   }

         }