Java中的多线程及其实现

什么是进程,什么是线程这里就不做赘述了,直接进入主题。

首先介绍一下一般程序的运行顺序,如图:

包括一个入口,一个出口和一个顺次执行的语句序列。

而包含线程对象的程序的执行顺序是:

线程与主线程共享CPU资源(交替使用)

线程一共有四种状态:新建(new),可运行(runnable),死亡(dead)以及阻塞(blocked)。

1. 创建线程

创建线程一般有两种方法:

1.1 继承 Thread 类并重写其中的 run() 方法

//定义一个线程类,它继承Thread类
class test_thread extends Thread {
	//重写run()方法
	public void run() {
		for (int i = 0; i != 100; ++i) {
			System.out.println("SubThread_1: " + i);
		}
	}
}

1.2 实现 Runnable 接口

//定义一个线程类,实现Runnable接口
class Runner implements Runnable {
	//实现run()方法
	public void run() {
		for (int i = 0; i != 100; ++i) {
			System.out.println("SubThread_2: " + i);
		}
	}
}

2. 线程的状态

2.1 新建(new)

//新建一个线程
		Thread thread = new Thread("test");

2.2 可运行状态(runnable)

//可运行状态
		thread.start();

2.3 死亡(dead)

//死亡,stop()函数不安全,不建议使用
		thread.stop();

2.4 阻塞(blocked)

//阻塞
		try {
			//以毫秒为单位
			Thread.sleep(100);
		} catch(InterruptedException e) {}

2.5 中断线程

//中断线程
		thread.interrupt();

3. 线程的调度

public static void main(String[] args) {
		//创建线程对象tt
		test_thread tt = new test_thread();
		//启动线程对象tt
		tt.start();
		//创建Runner类对象r
		Runner r = new Runner();
		//创建线程对象t,参考构造方法Thread(Runnable target)
		Thread t = new Thread(r);
		//启动线程对象t
		t.start();
		//主线程
		for(int i = 0; i != 100; ++i) {
			System.out.println("MainThread: " + i);
		}
	}

4. 运行结果

可以看到各条线程明显的交替运行,交替占用CPU资源,实现"并行性"。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值