Android多线程研究(1)——线程基础及源代码剖析
从今天起我们来看一下Android中的多线程的知识,Android入门easy,可是要完毕一个完好的产品却不easy,让我们从线程開始一步步深入Android内部。
一、线程基础回想
package com.maso.test; public class TraditionalThread { public static void main(String[] args) {
/*
* 线程的第一种创建方式
*/
Thread thread1 = new Thread(){
@Override
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(true){
System.out.println(Thread.currentThread().getName());
}
}
};
thread1.start(); /*
*线程的另外一种创建方式
*/
Thread thread2 = new Thread(new Runnable() { @Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while (true) {
System.out.println(Thread.currentThread().getName());
}
}
});
thread2.start(); /*
* 线程的调用优先级
*/
new Thread(new Runnable() { @Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(true){
System.out.println("Runnable");
}
}
}){
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(true){
System.out.println("Thread");
}
};
}.start();
}
}
上面代码中是我们都非常熟悉的线程的两种创建方式,假设对这些还感到陌生请先看Java线程基础。
打开Thread类的源代码能够看到Thread类有8个构造函数,我们先看看上面的两种构造函数的源代码。
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
在构造的时候直接调用了init方法
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
if (name == null) {
throw new NullPointerException("name cannot be null");
} Thread parent = currentThread();
SecurityManager security = System.getSecurityManager();
if (g == null) {
/* Determine if it's an applet or not */ /* If there is a security manager, ask the security manager
what to do. */
if (security != null) {
g = security.getThreadGroup();
} /* If the security doesn't have a strong opinion of the matter
use the parent thread group. */
if (g == null) {
g = parent.getThreadGroup();
}
} /* checkAccess regardless of whether or not threadgroup is
explicitly passed in. */
g.checkAccess(); /*
* Do we have the required permissions?
*/
if (security != null) {
if (isCCLOverridden(getClass())) {
security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
}
} g.addUnstarted(); this.group = g;
this.daemon = parent.isDaemon();
this.priority = parent.getPriority();
this.name = name.toCharArray();
if (security == null || isCCLOverridden(parent.getClass()))
this.contextClassLoader = parent.getContextClassLoader();
else
this.contextClassLoader = parent.contextClassLoader;
this.inheritedAccessControlContext = AccessController.getContext();
this.target = target;
setPriority(priority);
if (parent.inheritableThreadLocals != null)
this.inheritableThreadLocals =
ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
/* Stash the specified stack size in case the VM cares */
this.stackSize = stackSize; /* Set thread ID */
tid = nextThreadID();
}
里面的东西比較多,可是我们能够看到会初始化一个变量Runnable target;
以下我们再来看看run方法中是个什么东东?
@Override
public void run() {
if (target != null) {
target.run();
}
}
原来run方法中会先推断是否初始化了Runnable target变量,假设没有则空实现,假设target不为空则先运行Runnable接口中的run方法。有的朋友可能会猜想以下的代码会先调用Runnable接口中的run方法,然后才调用Thread实现类中的run方法。
/*
* 线程的调用优先级
*/
new Thread(new Runnable() { @Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(true){
System.out.println("Runnable");
}
}
}){
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(true){
System.out.println("Thread");
}
};
}.start();
事实上事实并不是如此,由于上面代码中是一个匿名内部类,实际上是一种从Thread的继承和实现,所以以下的run方法覆盖了Thread中的run方法,所以Runnable中的run方法根本不会运行。
以下再看看Runnable接口的源代码
public
interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
发现Runnable接口仅仅有一个抽象的run方法。
为什么要搞一个Runnable接口来实现多线程呢?从Thread继承不是更方便吗?Runnable接口有例如以下优势,所以我们经常会选择实现Runnable接口:
1、适合多个程序代码的线程去处理同一个资源。
public class ThreadTest1 extends Thread {
private int count = 5; public void run() {
for (int i = 0; i < 7; i++) {
if (count > 0) {
System.out.println("count= " + count--);
}
}
} public static void main(String[] args) {
//这样实际上是创建了三个互不影响的线程实例
ThreadTest1 t1 = new ThreadTest1();
ThreadTest1 t2 = new ThreadTest1();
ThreadTest1 t3 = new ThreadTest1();
t1.start();
t2.start();
t3.start();
}
}
public class ThreadTest1{ public static void main(String [] args) {
MyThread my = new MyThread();
//开启了三个线程,可是操作的是同一个run方法
new Thread(my, "1号窗体").start();
new Thread(my, "2号窗体").start();
new Thread(my, "3号窗体").start();
}
} class MyThread implements Runnable{ private int ticket = 5; //5张票 public void run() {
for (int i=0; i<=20; i++) {
if (this.ticket > 0) {
System.out.println(Thread.currentThread().getName()+ "正在卖票"+this.ticket--);
}
}
}
}
2、避免Java特性中的单根继承的限制。
3、能够保持代码和数据的分离(创建线程数和数据无关)。
4、更能体现Java面向对象的设计特点。
Android多线程研究(1)——线程基础及源代码剖析的更多相关文章
- Android多线程研究(6)——多线程之间数据隔离
在上一篇<Android多线程研究(5)--线程之间共享数据>中对线程之间的数据共享进行了学习和研究,这一篇我们来看看怎样解决多个线程之间的数据隔离问题,什么是数据隔离呢?比方说我们如今开 ...
- Android多线程研究(1)——线程基础及源码剖析
从今天起我们来看一下Android中的多线程的知识,Android入门容易,但是要完成一个完善的产品却不容易,让我们从线程开始一步步深入Android内部. 一.线程基础回顾 package com. ...
- JAVA与多线程开发(线程基础、继承Thread类来定义自己的线程、实现Runnable接口来解决单继承局限性、控制多线程程并发)
实现线程并发有两种方式:1)继承Thread类:2)实现Runnable接口. 线程基础 1)程序.进程.线程:并行.并发. 2)线程生命周期:创建状态(new一个线程对象).就绪状态(调用该对象的s ...
- Android多线程研究(3)——线程同步和相互排斥及死锁
为什么会有线程同步的概念呢?为什么要同步?什么是线程同步?先看一段代码: package com.maso.test; public class ThreadTest2 implements Runn ...
- Android多线程研究(9)——线程锁Lock
在前面我们在解决线程同步问题的时候使用了synchronized关键字,今天我们来看看Java 5.0以后提供的线程锁Lock. Lock接口的实现类提供了比使用synchronized关键字更加灵活 ...
- Android多线程研究(8)——Java5中Futrue获取线程返回结果
我们先来看一下ExecutorService中的执行方法: 在上一篇中我们使用了execute方法启动线程池中的线程执行,这一篇我们来看看submit方法的使用:submit提交一个返回值的任务用于执 ...
- Android多线程研究(7)——Java5中的线程并发库
从这一篇开始我们将看看Java 5之后给我们添加的新的对线程操作的API,首先看看api文档: java.util.concurrent包含许多线程安全.测试良好.高性能的并发构建块,我们先看看ato ...
- Android多线程研究(5)——线程之间共享数据
一.如果是每个线程都执行相同的代码,则可以使用同一个Runnable来实现共享 public class MultiThreadShareData { public static void main( ...
- Android多线程研究(3)——线程同步和互斥及死锁
为什么会有线程同步的概念呢?为什么要同步?什么是线程同步?先看一段代码: package com.maso.test; public class ThreadTest2 implements Runn ...
随机推荐
- 输出图片的php代码前面不能有空白行
第一行增加一个空白行,就至少会输出一个换行符在图片数据流的前面而图片是按图片流提供的信息显示的,前面多了内容就无法解析了.
- Storage Keepers
题意: n个仓库,m个人申请看管仓库,一个人可以看管多个仓库,一个仓库只能被一个人看管,每个人都有一个能力值,他看管的仓库的安全度U是能力值/看管仓库数,安全线L是U中的最小值,有多少能力公司发多少工 ...
- 记录一次cefsharp1输入法在win7下异常解决定位
最近几天都被基于cefSharp封装的浏览器控件搞疯了!对于cefSharp基本满足当前所做项目的需求,但是有一个问题一直困扰我,那就是系统中偶尔会出现输入法不能转换到中文.而且这个问题似乎没有什么规 ...
- 一致性Hash算法在Memcached中的应用
前言 大家应该都知道Memcached要想实现分布式只能在客户端来完成,目前比较流行的是通过一致性hash算法来实现.常规的方法是将server的hash值与server的总台数进行求余,即hash% ...
- IntelliJ IDEA 13 Keygen
import java.math.BigInteger; import java.util.Date; import java.util.Random; import java.util.zip.CR ...
- Ubuntu/CentOS使用BIND配置DNS服务器
------ubuntu server 12---------- 1.安装bind9 sudo apt-get -y install bind9 bind9utils 2.配置 /etc/bind/ ...
- 二叉树单色路径最长&&穿珠子
对树的操作,特别理解递归的好处. //对于一棵由黑白点组成的二叉树,我们需要找到其中最长的单色简单路径,其中简单路径的定义是从树上的某点开始沿树边走不重复的点到树上的 //另一点结束而形成的路径,而路 ...
- JS简单入门教程
JS简单教程 使用方法:放到任意html页面的head标签下 Test1方法弹出当前时间对话框 Test2方法for循环输出 Test3方法for(…in…)输出数组内容 <script typ ...
- MVC linq To SQL更新数据库操作
首先在视图中提交数据,使用Html.BeginForm() @using(Html.BeginForm()) { @Html.EditorForModel() //编辑模板.控制器中传过来的数据 &l ...
- Ubuntu上用快捷键关闭没有响应的程序
Linux 上有很多方法可以强制关闭无响应的程序,比如你可以通过按快捷键 Ctrl + Shift + T 来调出 Terminal 或者用 Ctrl + Shift + F1 进入 Console ...