多线程创建
1、线程的创建
1.1、继承 Tread 类实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public class myThread { public static void main(String[] args) { myThread1 m1 = new myThread1("你好1"); m1.start(); myThread1 m2 = new myThread1("你好2"); m2.start(); } }
class myThread1 extends Thread { private int tickets = 100; private String name; public myThread1(String name) { this.name = name; } @Override public void run() { while (this.tickets > 0) { System.out.println(this.name + "--------" + this.tickets--); } } }
|
1.2、实现 Runnable 接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| public class myThreadtwo { private static int aa = 10; public static void main(String[] args) { mythread1 m1 = new mythread1(aa); Thread t1 = new Thread(m1,"第一个"); Thread t2 = new Thread(m1,"第二个"); Thread t3 = new Thread(new Runnable() { @Override public void run() { System.out.println(aa); } }); t1.start(); t2.start(); t3.start(); } }
class mythread1 implements Runnable { private int tickets = 10; public mythread1(int t) { this.tickets = t; } @Override public void run() {
while (this.tickets > 0) { System.out.println(Thread.currentThread().getName() + "--------" + this.tickets--); } System.out.println(this);
} }
|
1.3、实现 Callable 接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| public class myThreadThree { private static int aa = 10; public static void main(String[] args) { myThreadnew m1 = new myThreadnew(aa); FutureTask future = new FutureTask(m1); Thread t1 = new Thread(future,"第一个"); Thread t2 = new Thread(future,"第二个"); Thread t3 = new Thread(new FutureTask(new Callable() { @Override public Object call() throws Exception { return null; } })); t1.start(); t2.start(); t3.start(); try { future.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
class myThreadnew implements Callable{ private int tickets = 10; public myThreadnew(int t) { this.tickets = t; } @Override public Object call() throws Exception { while (this.tickets > 0) { System.out.println(Thread.currentThread().getName() + "--------" + this.tickets--); } System.out.println(this); return null; } }
|
2、创建方式的比较
如果一个类继承 Thread,则不适合资源共享。但是如果实现了 Runable 接口的话,则很容易的实现资源共享。
相对来说,实现 Runnable 接口比继承 Thread 好。个人感觉完成同一个任务实现接口比较方便,跑不同的任务,继承 Thread 比较方便。
采用匿名内部类使用 Runnable 接口,会隐式的印用当前 Activity,会造成内存泄露。
1、实现 Runnable 的优势
可以避免 java 中的单继承的限制
线程池只能放入实现 Runable 或 callable 类线程,不能直接放入继承 Thread 的类
2、两者都有的
适合多个相同的程序代码的线程去处理同一个资源
增加程序的健壮性,代码可以被多个线程共享,代码和数据独立