多线程 thread/ runnable

1. 方案一:继承thread.

 1 package com.example.demo;
 2 
 3 
 4  
 5 //1. 方法1,继承thread类:Thread implements Runnable
 6 package com.example.demo;
 7 public class ThreadCreateDemo1 {
 8     public static void main(String[] args) {
 9         MyThread thread = new MyThread();
10         MyThread thread1 = new MyThread();
11         MyThread thread2 = new MyThread();
12         thread.start(); //该方法调用多次,出现IllegalThreadStateException
13         thread1.start(); //该方法调用多次,出现IllegalThreadStateException
14         thread2.start(); //该方法调用多次,出现IllegalThreadStateException
15     }
16 }
17 
18 class MyThread extends Thread {
19     @Override
20     public void run() {
21         //super.run();
22         System.out.println("hellow_world!");
23     }
24 }

2.方案二: 实现runnable.

 1 //2. 实现runnable:Thread(Runnable target)
 2 public class ThreadCreateDemo1 {
 3     public static void main(String[] args) {
 4         MyRunnable runnable = new MyRunnable();
 5         MyRunnable runnable1 = new MyRunnable();
 6         MyRunnable runnable2 = new MyRunnable();
 7         MyRunnable runnable3 = new MyRunnable();
 8        new Thread(runnable).start();
 9        new Thread(runnable1).start();
10        new Thread(runnable2).start();
11        new Thread(runnable3).start();
12        
13      }
14 }
15 
16 class MyRunnable implements Runnable {
17     public void run() {
18         System.out.println("通过Runnable创建的线程!");
19     }
20 }
21  

使用继承方式的好处是方便传参,你可以在子类里面添加成员变量,通过set方法设置参数或者通过构造函数进行传递,而如果使用Runnable方式,则只能使用主线程里面被声明为final的变量。不好的地方是Java不支持多继承,如果继承了Thread类,那么子类不能再继承其他类,而Runable则没有这个限制。前两种方式都没办法拿到任务的返回结果,但是Callable方式可以

猜你喜欢

转载自www.cnblogs.com/mengbin0546/p/12598653.html