您的位置:首页 > 其它

基本的线程机制(一)

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类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: