Java基本线程机制(一)


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

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

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

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


一、定义任务

定义任务有两种方法:

第一种:实现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");
	}
}




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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值