Android多线程研究(1)——线程基础及源码剖析
从今天起我们来看一下Android中的多线程的知识,Android入门容易,但是要完成一个完善的产品却不容易,让我们从线程开始一步步深入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多线程全面解析:IntentService用法&源码
前言 多线程的应用在Android开发中是非常常见的,常用方法主要有: 继承Thread类 实现Runnable接口 AsyncTask Handler HandlerThread IntentSer ...
- Android学习笔记_48_若水新闻客户端源码剖析
一.新闻客户端布局代码 1.1 主界面布局 使用GridView实现左右可滑动菜单项,使用标签HorizontalScrollView实现水平滚动条,将创建的GridView添加到布局文件中. < ...
- Netty学习笔记(三)——netty源码剖析
1.Netty启动源码剖析 启动类: public class NettyNioServer { public static void main(String[] args) throws Excep ...
- Android多线程研究(6)——多线程之间数据隔离
在上一篇<Android多线程研究(5)--线程之间共享数据>中对线程之间的数据共享进行了学习和研究,这一篇我们来看看怎样解决多个线程之间的数据隔离问题,什么是数据隔离呢?比方说我们如今开 ...
- 【Android 系统开发】CyanogenMod 13.0 源码下载 编译 ROM 制作 ( 手机平台 : 小米4 | 编译平台 : Ubuntu 14.04 LTS 虚拟机)
分类: Android 系统开发(5) 作者同类文章X 版权声明:本文为博主原创文章 ...
- Android斗地主棋牌游戏牌桌实现源码下载
本次给大家分享下Android斗地主棋牌游戏牌桌实现源码下载如下: 为了节约内存资源,每张扑克牌都是剪切形成的,当然这也是当前编程的主流方法. 1.主Activity package com.biso ...
- Android 图片加载框架Glide4.0源码完全解析(二)
写在之前 上一篇博文写的是Android 图片加载框架Glide4.0源码完全解析(一),主要分析了Glide4.0源码中的with方法和load方法,原本打算是一起发布的,但是由于into方法复杂性 ...
- Android 全面插件化 RePlugin 流程与源码解析
转自 Android 全面插件化 RePlugin 流程与源码解析 RePlugin,360开源的全面插件化框架,按照官网说的,其目的是“尽可能多的让模块变成插件”,并在很稳定的前提下,尽可能像开发普 ...
- linux线程池thrmgr源码解析
linux线程池thrmgr源码解析 1 thrmgr线程池的作用 thrmgr线程池的作用是提高程序的并发处理能力,在多CPU的服务器上运行程序,可以并发执行多个任务. 2 ...
随机推荐
- 跟着辛星用PHP的反射机制来实现插件
我的博文的前一篇解说了PHP的反射机制是怎么回事,假设读者还不清楚反射机制,能够搜索下或者看我的博文,都是不错的选择.我们開始解说一下怎么用PHP来实现插件机制.所谓插件机制.就是我们定义一个接口.即 ...
- Cannot use isset() on the result of an expression (you can use "null !== expression" instead)
if (isset($array[2])){ 抛出错误 Cannot use isset() on the result of an expression (you can use "nu ...
- PHP 实现断点续传的原理和方法
PHP 实现断点续传的原理和方法 0. http协议从1.1开始支持静态获取文件的部分内容,为多线程下载和断点续传提供了技术支持.它通过在Header里两个参数实现的,客户端发请求时对应的是Accep ...
- 用Zebra打造Linux下小型路由器
用Zebra打造Linux下小型路由器 现在的Internet网络相当庞大,不可能在不同的网络之间建立直接的连接,所以这时就必须用路由器为不同网络之间的通信提供路径选择.Linux下搭建路由器价格非常 ...
- git 常用命令(分支)
查看分支 git branch -r 修改分支名字dev-->test git branch -m dev test 切换分支dev git checkout dev 创建本地分支dev git ...
- 【Spring】Service 注入失败,空指针
service层的类都有用@Service标识,但报空指针,注入失败,很可能是因为spring的application配置和springmvc的配置文件配置错误,导致容器冲突了. spring和spr ...
- 洛谷 P2694 接金币
P2694 接金币 题目描述 在二维坐标系里,有N个金币,编号0至N-1.初始时,第i个金币的坐标是(Xi,Yi).所有的金币每秒向下垂直下降一个单位高度,例如有个金币当前坐标是(xf, yf),那么 ...
- 从头认识java-17.4 具体解释同步(3)-对象锁
这一章节我们接着上一章节的问题,给出一个解决方式:对象锁. 1.什么是对象锁? 对象锁是指Java为临界区synchronized(Object)语句指定的对象进行加锁,对象锁是独占排他锁. 2.什么 ...
- unity3d 改动gui label颜色,定义颜色需除以256
GUIStyle titleStyle2 = new GUIStyle(); titleStyle2.fontSize = 20; titleStyle2.normal.textColor = new ...
- Java 函数的参数说
java函数参数传递的到底是值还是引用对确实容易让人迷糊.而很多时候因为对这个问题的模糊甚至造成一些错误.最常见的说法是基本类型传的是值,对象传的引用.对于基本类型,大家都达成共识,没有什么可以争论的 ...