Java学习:线程基础(一)

线程概念:

1、线程是轻量级的进程

2、线程没有独立的地址空间(内存空间)

3、线程由进程创建(寄生于进程)

4、一个进程可以拥有多个线程(多线程编程)

5、线程有几种状态:

a、新建状态

b、就绪状态

c、运行状态

d、阻塞状态

e、死亡状态

线程如何使用

在java中一个类要当做线程使用有两种方法:

1、继承Thread类,并重写run函数

案例1:编写一个程序,该程序可以每隔一秒在控制台输出“hello,world”。

public class ThreadTest {
	public static void main(String[] args) {// 创建一个Cat对象
		Cat cat = new Cat();
		// 启动线程,会导致run函数的运行
		cat.start();

	}
}
class Cat extends Thread {
	// 重写run函数
	public void run() {
		while (true) {
			// 休眠一秒(1000毫秒)线程进入阻塞状态
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("hello,world");
		}
	}
}

执行结果:

案例2:编写一个程序,该程序可以每隔一秒在控制台输出“hello,world”,当输出10次后,自动退出。

public class ThreadTest {
	public static void main(String[] args) {// 创建一个Cat对象
		Cat cat = new Cat();
		// 启动线程,会导致run函数的运行
		cat.start();

	}
}

class Cat extends Thread {
	// 重写run函数
	int times = 0;

	public void run() {
		while (true) {
			// 休眠一秒(1000毫秒)线程进入阻塞状态
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			times++;
			System.out.println("hello,world" + times);
			if (times == 10) {
				break;
			}
		}

	}
}

执行结果:

 

2、实现Runnable接口,并重写run函数(解决Java不能多重继承的问题)

public class RunnableTest {

	public static void main(String[] args) {
		Cat cat = new Cat();
		// 注意启动方法
		Thread t = new Thread(cat);
		t.start();
	}
}

class Cat implements Runnable {
	// 重写run函数
	int times = 0;

	public void run() {
		while (true) {
			// 休眠一秒(1000毫秒)线程进入阻塞状态
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			times++;
			System.out.println("hello,world" + times);
			if (times == 10) {
				break;
			}
		}

	}
}

注意实现Runnable接口创建多线程时线程的启动方式。

执行结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值