java 启动线程的 3 种方式对比分析
这里有新鲜出炉的 Java 设计模式, 程序狗速度看过来!
Java 程序设计语言
java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言, 是由 Sun Microsystems 公司于 1995 年 5 月推出的 Java 程序设计语言和 Java 平台 (即 JavaEE(j2ee), JavaME(j2me), JavaSE(j2se)) 的总称
这篇文章主要为大家对比分析了 java 启动线程的 3 种方式, 具有一定的参考价值, 感兴趣的小伙伴们可以参考一下
1. 继承 Thread
- public class java_thread extends Thread{
- public static void main(String args[])
- {
- (new java_thread()).run();
- System.out.println("main thread run");
- }
- public synchronized void run()
- {
- System.out.println("sub thread run");
- }
- }
2. 实现 Runnable 接口
- public class java_thread implements Runnable{
- public static void main(String args[])
- {
- (new Thread(new java_thread())).start();
- System.out.println("main thread run");
- }
- public void run()
- {
- System.out.println("sub thread run");
- }
- }
3. 直接在函数体使用
- void java_thread() {
- Thread t = new Thread(new Runnable() {
- public void run() {
- mSoundPoolMap.put(index, mSoundPool.load(filePath, index));
- getThis().LoadMediaComplete();
- }
- });
- t.start();
- }
4. 比较:
实现 Runnable 接口优势:
1)适合多个相同的程序代码的线程去处理同一个资源
2)可以避免 Java 中的单继承的限制
3)增加程序的健壮性, 代码可以被多个线程共享, 代码和数据独立
继承 Thread 类优势:
1)可以将线程类抽象出来, 当需要使用抽象工厂模式设计时
2)多线程同步
在函数体使用优势
1)无需继承 thread 或者实现 Runnable, 缩小作用域
来源: http://www.phperz.com/article/18/0205/359021.html