多线程发送操作之一:运行一个线程的格式化代码(Specifying the Code to Run on a Thread)
来源:互联网 发布:linux怎么运行sh脚本 编辑:程序博客网 时间:2024/03/29 22:23
<最近在学习多线程的知识>
这篇文章文章展示了如何实现一个Runnable类,在独立线程中该类在它的Runnable.run()方法中运行代码。你也可以传递一个Runnable到另外一个对象,可以把它加载到一个线程上然后运行。一个或多个Runnable对象完成一个特殊的操作有时被称为一个线程。
Thread和Runnable就他们本身而言是基本的类,只有有限的能力。相反,他们有强大的Android类作为基础,这些类如HandlerThread,AsyncTask,和IntentService。Thread和Runnable也是ThreadPoolExecutor类的基础。该类自动管理线程和任务队列,甚至可以同时运行多个线程。
定义一个类实现Runnable
完成一个实现Runnable接口的类很简单,如示例:
public class PhotoDecodeRunnable implements Runnable { ... @Override public void run() { /* * Code you want to run on the thread goes here */ ... } ...}
完成run()方法
在这个类中,Runnable.run()方法包含要执行的代码。通常说,任何代码都可以放在Runnable中。记住,因为Runnable不可以在主线程中运行,所以它不可以直接修改UI对象例如View对象。为了实现与主线程通信,你必须使用Communication with the UI Thread一章中描述的技巧。
在run()方法的开始,通过调用Process.setThreadPriority()来设置线程的优先级为THREAD_PRIORITY_BACKGROUND。这种方式减少了Runnable对象线程与主线程之间的资源竞争。
通过调用Thread.currentThread()方法,你还应该保存Runnable对象线程的一个引用在Runnable里面。
下面的一段展示了如何建立一个run()方法:
class PhotoDecodeRunnable implements Runnable {... /* * Defines the code to run for this task. */ @Override public void run() { // Moves the current Thread into the background android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); ... /* * Stores the current Thread in the PhotoTask instance, * so that the instance * can interrupt the Thread. */ mPhotoTask.setImageDecodeThread(Thread.currentThread()); ... }...}
- 多线程发送操作之一:运行一个线程的格式化代码(Specifying the Code to Run on a Thread)
- Specifying the Code to Run on a Thread
- 多线程之三:在线程池中的线程运行代码 (Running Code on a Thread Pool Thread)
- How to stop a Thread(怎样停止一个线程)
- JAVA之旅(十二)——Thread,run和start的特点,线程运行状态,获取线程对象和名称,多线程实例演示,使用Runnable接口
- JAVA多线程—传统线程机制-运行Thread.run()还是Runnable.run()
- Excel: How to run C# code behind with a click of a button on a Worksheet, without VBA code
- #371 – 指定日历控件显示的日期时间(Specifying a Default Date for a Calendar Control to Display)
- Java Thread 多线程 操作线程
- Java Thread 多线程 操作线程
- Java Thread 多线程 操作线程
- How to add a exe application run as a service(如何将一个可执行程序当作服务运行)?
- Gstreamer插件教程2.2—编写一个插件(Writing a Plugin):详解pads(Specifying the pads)
- IOS真机切换UI界面时,出现“Only run on the main thread” 的解决方法
- 覆盖Thread类的run()方法使用线程
- 通过重写Thread的run()方法显示新线程
- Tried to obtain the web lock from a thread解决方法之一
- Tried to obtain the web lock from a thread解决方法之一
- notepad++6.5中文绿色汉化版下载
- PB9核心之——数据窗口对象使用
- opencv基本操作
- Java判断给定日期哪个大,哪个小;日期类型:YYYY-MM-DD
- MTK android 可修改IMEI方法
- 多线程发送操作之一:运行一个线程的格式化代码(Specifying the Code to Run on a Thread)
- Java.util.Timer深入JDK代码及工作原理
- makefile $(filter PATTERN...,TEXT)
- Linux修改默认启动级别
- 保健品消费者需求调研内容及设计
- SpringMVC深入浅出入门教程
- 数据库和数据仓库区别
- 让vim编辑器显示行号的方法
- 博客开启