多线程的实现方式

 1 public class ThreadDemo1 {
 2     public static void main(String[] args) {
 3         /*多线程的实现方式一:
 4          *   1.写一个Thread的子类2.重写run方法3.创建子类对象4.启动线程
 5          */
 6         ThreadClassBase p=new ThreadClassBase();
 7         p.setName("线程一");
 8         p.start();
 9         ThreadClassBase p1=new ThreadClassBase();
10         p1.setName("线程二");
11         p1.start();
12         
13     }
14 
15 }
16 
17 //Thread子类
18 public class ThreadClassBase extends Thread {
19     @Override
20     public void run() {
21         for(int i=0;i<100;i++){
22             System.out.println(this.getName()+":"+i);
23         }
24     }
25 
26 }
 1 public class ThreadDemo2 {
 2     public static void main(String[] args) {
 3         /*多线程的实现方式二:
 4          * 1.实现Runnable接口2.重写接口中run方法
 5          * 3.创建Thread对象,将实现接口的类作为参数给Thread构造方法
 6          * 4.启动线程,运行重写接口中的run方法
 7          */
 8         ThreadClassBase2 tcb=new ThreadClassBase2();
 9         Thread t=new Thread(tcb);
10         t.setName("线程一");
11         t.start();
12         Thread t1=new Thread(tcb);//如果构造方法中参数不同,可以另外创建一个对象
13         t1.setName("线程二");
14         t1.start();
15     }
16 
17 }
18 
19 //实现Runnable接口的类
20 public class ThreadClassBase2 implements Runnable {
21 
22     public void run() {
23         for(int i=0;i<100;i++){
24             Thread t=Thread.currentThread();
25             System.out.println(t.getName()+":"+i);
26         }
27         
28     }
29 
30 }

 有第二种实现方式的原因:

  解决Java中单一继承的问题

posted @ 2020-02-11 14:00  /*nobody*/  阅读(172)  评论(0编辑  收藏  举报