从今天起我们来看一下Android中的多线程的知识,Android入门easy,可是要完毕一个完好的产品却不easy,让我们从线程開始一步步深入Android内部。

一、线程基础回想

  1. package com.maso.test;
  2.  
  3. public class TraditionalThread {
  4.  
  5. public static void main(String[] args) {
  6. /*
  7. * 线程的第一种创建方式
  8. */
  9. Thread thread1 = new Thread(){
  10. @Override
  11. public void run() {
  12. try {
  13. sleep(1000);
  14. } catch (InterruptedException e) {
  15. e.printStackTrace();
  16. }
  17. while(true){
  18. System.out.println(Thread.currentThread().getName());
  19. }
  20. }
  21. };
  22. thread1.start();
  23.  
  24. /*
  25. *线程的另外一种创建方式
  26. */
  27. Thread thread2 = new Thread(new Runnable() {
  28.  
  29. @Override
  30. public void run() {
  31. try {
  32. Thread.sleep(1000);
  33. } catch (InterruptedException e) {
  34. e.printStackTrace();
  35. }
  36. while (true) {
  37. System.out.println(Thread.currentThread().getName());
  38. }
  39. }
  40. });
  41. thread2.start();
  42.  
  43. /*
  44. * 线程的调用优先级
  45. */
  46. new Thread(new Runnable() {
  47.  
  48. @Override
  49. public void run() {
  50. try {
  51. Thread.sleep(1000);
  52. } catch (InterruptedException e) {
  53. e.printStackTrace();
  54. }
  55. while(true){
  56. System.out.println("Runnable");
  57. }
  58. }
  59. }){
  60. public void run() {
  61. try {
  62. sleep(1000);
  63. } catch (InterruptedException e) {
  64. e.printStackTrace();
  65. }
  66. while(true){
  67. System.out.println("Thread");
  68. }
  69. };
  70. }.start();
  71. }
  72. }

上面代码中是我们都非常熟悉的线程的两种创建方式,假设对这些还感到陌生请先看Java线程基础。

打开Thread类的源代码能够看到Thread类有8个构造函数,我们先看看上面的两种构造函数的源代码。

  1. public Thread() {
  2. init(null, null, "Thread-" + nextThreadNum(), 0);
  3. }

在构造的时候直接调用了init方法

  1. private void init(ThreadGroup g, Runnable target, String name,
  2. long stackSize) {
  3. if (name == null) {
  4. throw new NullPointerException("name cannot be null");
  5. }
  6.  
  7. Thread parent = currentThread();
  8. SecurityManager security = System.getSecurityManager();
  9. if (g == null) {
  10. /* Determine if it's an applet or not */
  11.  
  12. /* If there is a security manager, ask the security manager
  13. what to do. */
  14. if (security != null) {
  15. g = security.getThreadGroup();
  16. }
  17.  
  18. /* If the security doesn't have a strong opinion of the matter
  19. use the parent thread group. */
  20. if (g == null) {
  21. g = parent.getThreadGroup();
  22. }
  23. }
  24.  
  25. /* checkAccess regardless of whether or not threadgroup is
  26. explicitly passed in. */
  27. g.checkAccess();
  28.  
  29. /*
  30. * Do we have the required permissions?
  31. */
  32. if (security != null) {
  33. if (isCCLOverridden(getClass())) {
  34. security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
  35. }
  36. }
  37.  
  38. g.addUnstarted();
  39.  
  40. this.group = g;
  41. this.daemon = parent.isDaemon();
  42. this.priority = parent.getPriority();
  43. this.name = name.toCharArray();
  44. if (security == null || isCCLOverridden(parent.getClass()))
  45. this.contextClassLoader = parent.getContextClassLoader();
  46. else
  47. this.contextClassLoader = parent.contextClassLoader;
  48. this.inheritedAccessControlContext = AccessController.getContext();
  49. this.target = target;
  50. setPriority(priority);
  51. if (parent.inheritableThreadLocals != null)
  52. this.inheritableThreadLocals =
  53. ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
  54. /* Stash the specified stack size in case the VM cares */
  55. this.stackSize = stackSize;
  56.  
  57. /* Set thread ID */
  58. tid = nextThreadID();
  59. }

里面的东西比較多,可是我们能够看到会初始化一个变量Runnable  target;

以下我们再来看看run方法中是个什么东东?

  1. @Override
  2. public void run() {
  3. if (target != null) {
  4. target.run();
  5. }
  6. }

原来run方法中会先推断是否初始化了Runnable target变量,假设没有则空实现,假设target不为空则先运行Runnable接口中的run方法。有的朋友可能会猜想以下的代码会先调用Runnable接口中的run方法,然后才调用Thread实现类中的run方法。

  1. /*
  2. * 线程的调用优先级
  3. */
  4. new Thread(new Runnable() {
  5.  
  6. @Override
  7. public void run() {
  8. try {
  9. Thread.sleep(1000);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. while(true){
  14. System.out.println("Runnable");
  15. }
  16. }
  17. }){
  18. public void run() {
  19. try {
  20. sleep(1000);
  21. } catch (InterruptedException e) {
  22. e.printStackTrace();
  23. }
  24. while(true){
  25. System.out.println("Thread");
  26. }
  27. };
  28. }.start();

事实上事实并不是如此,由于上面代码中是一个匿名内部类,实际上是一种从Thread的继承和实现,所以以下的run方法覆盖了Thread中的run方法,所以Runnable中的run方法根本不会运行。

以下再看看Runnable接口的源代码

  1. public
  2. interface Runnable {
  3. /**
  4. * When an object implementing interface <code>Runnable</code> is used
  5. * to create a thread, starting the thread causes the object's
  6. * <code>run</code> method to be called in that separately executing
  7. * thread.
  8. * <p>
  9. * The general contract of the method <code>run</code> is that it may
  10. * take any action whatsoever.
  11. *
  12. * @see java.lang.Thread#run()
  13. */
  14. public abstract void run();
  15. }

发现Runnable接口仅仅有一个抽象的run方法。

为什么要搞一个Runnable接口来实现多线程呢?从Thread继承不是更方便吗?Runnable接口有例如以下优势,所以我们经常会选择实现Runnable接口:

1、适合多个程序代码的线程去处理同一个资源。

  1. public class ThreadTest1 extends Thread {
  2. private int count = 5;
  3.  
  4. public void run() {
  5. for (int i = 0; i < 7; i++) {
  6. if (count > 0) {
  7. System.out.println("count= " + count--);
  8. }
  9. }
  10. }
  11.  
  12. public static void main(String[] args) {
  13. //这样实际上是创建了三个互不影响的线程实例
  14. ThreadTest1 t1 = new ThreadTest1();
  15. ThreadTest1 t2 = new ThreadTest1();
  16. ThreadTest1 t3 = new ThreadTest1();
  17. t1.start();
  18. t2.start();
  19. t3.start();
  20. }
  21. }
  1. public class ThreadTest1{
  2.  
  3. public static void main(String [] args) {
  4. MyThread my = new MyThread();
  5. //开启了三个线程,可是操作的是同一个run方法
  6. new Thread(my, "1号窗体").start();
  7. new Thread(my, "2号窗体").start();
  8. new Thread(my, "3号窗体").start();
  9. }
  10. }
  11.  
  12. class MyThread implements Runnable{
  13.  
  14. private int ticket = 5; //5张票
  15.  
  16. public void run() {
  17. for (int i=0; i<=20; i++) {
  18. if (this.ticket > 0) {
  19. System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
  20. }
  21. }
  22. }
  23. }

2、避免Java特性中的单根继承的限制。

3、能够保持代码和数据的分离(创建线程数和数据无关)。

4、更能体现Java面向对象的设计特点。

Android多线程研究(1)——线程基础及源代码剖析的更多相关文章

  1. Android多线程研究(6)——多线程之间数据隔离

    在上一篇<Android多线程研究(5)--线程之间共享数据>中对线程之间的数据共享进行了学习和研究,这一篇我们来看看怎样解决多个线程之间的数据隔离问题,什么是数据隔离呢?比方说我们如今开 ...

  2. Android多线程研究(1)——线程基础及源码剖析

    从今天起我们来看一下Android中的多线程的知识,Android入门容易,但是要完成一个完善的产品却不容易,让我们从线程开始一步步深入Android内部. 一.线程基础回顾 package com. ...

  3. JAVA与多线程开发(线程基础、继承Thread类来定义自己的线程、实现Runnable接口来解决单继承局限性、控制多线程程并发)

    实现线程并发有两种方式:1)继承Thread类:2)实现Runnable接口. 线程基础 1)程序.进程.线程:并行.并发. 2)线程生命周期:创建状态(new一个线程对象).就绪状态(调用该对象的s ...

  4. Android多线程研究(3)——线程同步和相互排斥及死锁

    为什么会有线程同步的概念呢?为什么要同步?什么是线程同步?先看一段代码: package com.maso.test; public class ThreadTest2 implements Runn ...

  5. Android多线程研究(9)——线程锁Lock

    在前面我们在解决线程同步问题的时候使用了synchronized关键字,今天我们来看看Java 5.0以后提供的线程锁Lock. Lock接口的实现类提供了比使用synchronized关键字更加灵活 ...

  6. Android多线程研究(8)——Java5中Futrue获取线程返回结果

    我们先来看一下ExecutorService中的执行方法: 在上一篇中我们使用了execute方法启动线程池中的线程执行,这一篇我们来看看submit方法的使用:submit提交一个返回值的任务用于执 ...

  7. Android多线程研究(7)——Java5中的线程并发库

    从这一篇开始我们将看看Java 5之后给我们添加的新的对线程操作的API,首先看看api文档: java.util.concurrent包含许多线程安全.测试良好.高性能的并发构建块,我们先看看ato ...

  8. Android多线程研究(5)——线程之间共享数据

    一.如果是每个线程都执行相同的代码,则可以使用同一个Runnable来实现共享 public class MultiThreadShareData { public static void main( ...

  9. Android多线程研究(3)——线程同步和互斥及死锁

    为什么会有线程同步的概念呢?为什么要同步?什么是线程同步?先看一段代码: package com.maso.test; public class ThreadTest2 implements Runn ...

随机推荐

  1. 锁之“重量级锁”Synchronized

    一.Synchronized的基本使用 Synchronized是Java中解决并发问题的一种最常用的方法,也是最简单的一种方法.Synchronized的作用主要有三个:(1)确保线程互斥的访问同步 ...

  2. android技巧:EditText输入错误时该怎样提示用户

    验证用户输入内容(EditText)应该及时准确的告诉用户,那么在Android系统中提示用户通常有以下做法: 1) 使用Toast提示 1 Toast.makeText(this, "邮箱 ...

  3. c++中调用cygwin/x使用ncl

    1.C++中调用程序:   ShellExecute(NULL,L"open",L"cmd.exe",L"/c d: & cd cygwin ...

  4. python2.7系列安装失败的办法

    在windows系统上安装python时出现"there is a problem with your Windows installer package. A program run as ...

  5. 多态.xml

    pre{ line-height:1; color:#1e1e1e; background-color:#f0f0f0; font-size:16px;}.sysFunc{color:#627cf6; ...

  6. 【VC】VC工具栏图标合并工具(非tbcreator和visual toolbar)

    VC开发难免会用到toolbar,在没有美工的时候,大部分时间我们只能自己上. 第一个方法:fireworks/photoshop平铺.现在的图片资源大多为背景透明的png图片,虽然fireworks ...

  7. Yii 1.11 获取当前的模块名 控制器名 方法名

    $this->module->id; #模块名$this->action->id; #方法名$this->uniqueId; #控制器名称 Yii: 获取当前模块名.控制 ...

  8. onAttachedToWindow()在整个Activity生命周期的位置及使用

    onAttachedToWindow在整个Activity的生命周期中占据什么位置? 为什么要在onAttachedToWindow中修改窗口尺寸? 一.onAttachedToWindow在Acti ...

  9. 第三百六十天 how can I 坚持

    看了两集linux视频,有点懵啊,下班还想走去天安门,想啥呢,太远了. 居住证没法办,哎,要入职两年. 考研要是也不能考,这一年也太.. 点不会那么背吧. 好像没啥了,睡觉.

  10. log4j:ERROR LogMananger.repositorySelector was null likely due to error in class reloading, using NOPLoggerRepository.

    The reason for the error is a new listener in Tomcat 6.0.24. You can fix this error by adding this l ...