JAVA 两种方法实现多线程(继承Thread和实现Runnable接口)

时间:2022-08-04 17:32:24
 1 package h14;
 2 
 3 public class Demo {
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         Thread cat = new Cat();
11         cat.start();
12         Runnable dog = new Dog();
13         Thread t = new Thread(dog);
14         t.start();
15     }
16 
17 }
18 
19 class Cat extends Thread{
20 
21     @Override
22     public void run() {
23         // TODO Auto-generated method stub
24         super.run();
25         int i = 0;
26         while(true){
27             try {
28                 i++;
29                 Thread.sleep(1000);
30             } catch (InterruptedException e) {
31                 // TODO Auto-generated catch block
32                 e.printStackTrace();
33             }
34             System.out.println(i);
35         }
36     }
37     
38 }
39 
40 class Dog implements Runnable{
41 
42     @Override
43     public void run() {
44         // TODO Auto-generated method stub
45         System.out.print("hello");
46         
47     }
48     
49 }