您的位置:首页 > 编程语言 > Java开发

Java基本线程机制(一)

2013-12-17 12:58 465 查看
任务:线程中需要执行的代码或功能。

线程驱动:创建一个新的线程,并且执行绑定到该线程的任务。

线程:共享内存。多个进程可以访问寄存器中的同一个变量。

进程:不共享内存。只能访问自己内存中的变量。

一、定义任务

定义任务有两种方法:

第一种:实现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;
}
private String status(){
return "#" + id + "(" + (countDown > 0 ? countDown : "liftoff") + "),";
}
@Override
public void run() {
while(countDown-- > 0){
System.out.print(status());
Thread.yield();
}
}

第二种:继承Thread类,重写run()方法。
public class SimpleThread extends Thread {
private int countDown = 5;
private static int threadCount = 0;
public SimpleThread(){
super(Integer.toString(++threadCount));
start();
}
public void run(){
while(true){
System.out.println(this);
if(--countDown == 0)
return;
}
}
public static void main(String[] args){
for(int i = 0; i < 5; i++){
new SimpleThread();
}
}
}


这两种方法实现的run()方法都不是线程驱动的,即这两个run()方法就是普通的方法,可以直接调用。如:
public static void main(String[] args){
LiftOff lo = new LiftOff();
lo.run();//直接调用run()方法
}

这样run()方法不会在子线程中执行,而是在main()方法的线程里执行。

二、为线程附着任务

方法为将一个任务对象(Runnable对象)构造一个Thread对象,则这个任务就会附着到这个Thread对象,当这个Thread对象驱动线程时,会在线程里执行这个任务。

public class BasicThread {
public static void main(String[] args) {
Thread thread = new Thread(new LiftOff());
thread.start(); //驱动线程,执行任务。
System.out.println("end");

}

}
public class MoreBasicThread {
public static void main(String[] args){
for(int i = 0; i < 5; i++){
new Thread(new LiftOff()).start();
}
System.out.println("wait for lauch");
}
}


任务:线程中需要执行的代码或功能。

线程驱动:创建一个新的线程,并且执行绑定到该线程的任务。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 线程 thread