Java 多线程之Thread类继承

Thread类中最重要的方法是run(),run()是属于那些会与程序中其他线程“并发”或“同时”执行的代码。

线程并不是按照它们创建时的顺序执行的。事实,CPU处理一个现有线程集的顺序是不确定的,除非我们使用Thread中的setPriority()方法调整它们的优先级。

public class SimpleThread extends Thread{
	private int countDown = 5;
	private int threadNumber;
	private static int threadCount = 0;
	public SimpleThread(){
		threadNumber = ++threadCount;
		System.out.println("Making " + threadNumber);
	}
	public void run(){
		while(true){
			System.out.println("Thread " + threadNumber + "(" + countDown + ")");
			if(--countDown == 0) return;
		}
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int i = 0; i < 5; i++)
			new SimpleThread().start();
	System.out.println("All Thread Started");
	}
}

上面这个例子中SimpleThread继承了Thread类,并覆盖了run()方法,每通过一次循环,计数就减一,计数为0时进程中止。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值