Java线程的创建与简单实现

本文介绍了如何在Java中使用线程机制实现并发编程。通过Runnable接口定义任务,利用Thread类启动和执行任务,演示了简单的倒计时示例。

程序的一个重要指标就是在正确性的基础上其运行的速度,那么并发就是提高程序运行速度的重要方法。于是,实现并发的最直接的方式就是在操作系统级别使用“进程”。

一. 线程机制:

1. 定义任务:

在Java中,线程驱动任务可以由Runnable接口来提供。定义任务指的是实现接口Runnable并重写run()方法,一个简单的倒计时例子:

public class LiftOff implements Runnable {
protected int count = 10;
private static int taskcount = 0;
private final int id = taskcount++;
public LiftOff(int count) {
this.count = count;
}
public String status() {
return "#" + id + "(" + (count > 0 ? count : "LiftOff !") + ").";
}
public void run() {
while(count-- > 0) {
System.out.println(status());
Thread.yield();
}
}

}

那么在main()函数中调用它:

public class MainThread {
public static void main(String[] args) {
LiftOff liftOff = new LiftOff();
liftOff.run();
}

}

在控制台的输出则为:#0(9).#0(8).#0(7).#0(6).#0(5).#0(4).#0(3).#0(2).#0(1).#0(Liftoff !)

当从Runnable导出一个类时,那么必须重写run()方法,在run()方法定义自己的任务代码。

2. 当然,我们也可以将任务交给一个Thread构造器,即用Thread来驱动对象LiftOff,代码如下:

public class MainThread {
public static void main(String[] args) {
Thread thread = new Thread(new LiftOff());
thread.start();
}

}

调用Thread的start()方法初始化该线程,并调用线程中run()方法,启动该任务。

还可以添加更多的线程驱动更多的任务,代码如下:

public class MoreThreads{
public static void main(String[] args) {
for(int i = 0; i < 5; i++) {
new Thread(new LiftOff()).start();
}
}

}

输出说明不同的任务执行在线程中混在了一起,若machine中有多个处理器,则线程调度器会在这些处理器之间分发线程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值