基本的线程机制(一)
2015-11-19 12:36
288 查看
java编程思想中说道:并发编程使我们可以将程序划分为多个分离的,独立运行的任务。通过使用多线程机制,这些独立任务(也被称为子任务)中的每一个都将由执行线程来驱动。一个线程就是在进程中的一个单一的顺序控制流,因此,单个进程可以拥有多个并发执行的任务,但是你的程序使得每个任务都好像有其自己的cpu一样。其底层机制是切分cpu时间,通常程序员不需要考虑他。 针对以上提出,可以分为任务,执行线程,执行线程的控制流来讨论。
任务
think in java提到将程序划分为多个分离的,独立运行的任务。线程可以驱动任务,因此在java中需要一个描述任务的方式.这里通常有三种方法实现Runnable接口,Callable接口,继承Thread类。对于这里我们详细讨论Runnable接口
public interface Runnable { public abstract void run(); }
Runnable中有一个抽象run方法,让其子类实现这个方法下面举一个实例
public class Liftoff implements Runnable{ protected int countDown = 10; private static int taskCount=0; private final int id=taskCount++; public Liftoff(){ } public Liftoff(int countDown){ this.countDown=countDown; } public String status(){ return "#" +id +"("+(countDown >0 ?countDown :"Liftoff!")+"), "; } @Override public void run() { while(countDown-->0){ System.out.println(status()); Thread.yield(); } } }
Liftoff类实现了Runnable接口,重写run方法,Thread.yield后面会介绍
在这里我们把任务定义出来,现在我们缺少什么?现在就缺少一个线程驱动调用这个方法。
我们这里采用Main方法调用,Main方法实质上也是一个线程:
public class MainThread { public static void main(String[] args) { Liftoff launch=new Liftoff(); launch.run(); } }/*out #0(9), #0(8), #0(7), #0(6), #0(5), #0(4), #0(3), #0(2), #0(1), #0(Liftoff!), */
在这里对任务的基本定义就结束,接下来学习Thread类
相关文章推荐
- View setTag()与getTag();
- Linux服务之ssh防暴力破解
- url加密调研报告
- ArrayAdapter实现仿QQ左右发送消息显示
- FFMpeg+SDL多线程播放器
- Zmodem transfer canceled by remote side问题的解决办法!
- oracle
- linux中find批量删除空文件及空文件夹脚本
- 阿里云--域名,主机,备案都配置好了,就是不能访问网站的解决方案
- 单例模式(多线程不安全,序列化不安全,反射不安全实例)
- mesos上安装hadoop过程简介
- Spring_Security_3.0.1中文参考文档 Chapter 8.核心安全过滤器
- [leetcode 223] Rectangle Area
- 配置MySQL远程访问权限
- dom事件
- android 四大组件service 音乐播放器的实现
- QtCreator下复制文件夹的一个BUG
- 运算符
- Centos平台Supervisord全攻略
- 希尔排序c语言版