java---并发

什么是线程

1.将执行任务的代码放在一个类的run方法
public interface Runnable
{
	void run();
}

Runnable r = ()->{task code};
2.从这个Runnable构造一个Thread对象
var t = new Thread(r);
3.启动线程
t.start();
综合
Runnable r = ()->
{
	try
	{
		for(int i = 0; i < STEPS; i++)
		{
			double amount = MAX_AMOUNT * Math.random();
			bank.transfer(0, 1, amount);
			Thread.sleep((int)(DELAY * Math.random()));
		}
	}
	catch(InterruptedException e)
	{}
};

var t = new Thread(r);
t.start();

线程状态

1.New
2.Runnable
3.Blocked
4.Waiting
5.Timed waiting
6.Terminated
- 新建线程
new创建一个新线程,但还没运行。
- 可运行线程
一旦调start方法,线程就处于可运行状态。
可运行状态可以被处理器调度运行,但不保证正在被调度运行。
- 阻塞和等待线程
1.当一个线程试图获取一个内部的对象锁,而此锁目前被其他线程占有,该线程就会被阻塞。
当所有其他线程都释放了这个锁,且线程调度器允许该线程持有这个锁时,它将变成非阻塞状态。
2.当线程等待另一个线程通知调度器出现一个条件时,这个线程会进入等待状态。
3.有几个方法有超时参数,调用这些方法会让线程进入计时等待状态。
- 终止线程
1.run方法正常退出
2.未捕获异常而终止了run方法。

线程属性

- 中断线程
当线程的run方法执行方法体中最后一条语句后再执行return语句返回时,
或出现了方法中没有捕获的异常时,线程将终止。
interrupt方法可用来请求终止一个线程。
当对一个线程调interrupt方法时,会设置线程的中断状态。
每个线程应不时地检查这个标志,
while (!Thread.currentThread().isInterrupted() && more work to do)
{
	do more work
}
当在一个被sleep或wait调用阻塞的线程上调interrupt方法时,
那个阻塞调用将被一个InterruptedException异常中断。
Runnable r = ()->
{
	try
	{
		...
		while(!Thread.currentThread().isInterrupted() && more work to do)
		{
			do more work
		}
	}
	catch(InterruptedException e)
	{
		// thread was interrupted during sleep or wait
	}
	finally
	{
		cleanup, if required	
	}
	// exiting the run method terminates the thread
}
如果设置了中断状态,此时若调用sleep方法,它不会休眠。
实际上,它会清除中断状态并抛出InterruptedException。
void mySubTask()
{
	...
	try
	{
		sleep(delay);
	}
	catch(InterruptedException e)
	{
		Thread.currentThread().interrupt();
	}
}

void mySubTask() throws InterruptedException
{
	...
	sleep(delay);
	...
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

raindayinrain

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值