您的位置:首页 > 其它

Thread 状态及volatile关键字作用join方法的使用

2017-11-16 10:00 393 查看
线程状态 Thread.State

1 Thread.State BLOCKED 阻塞状态

Thread state for a thread blocked waiting for a monitor lock. A thread in the blocked state is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling Object.wait.

线程正在等待线程锁的阻塞状态,阻塞状态正在等待线程锁进入同步方法或者同步代码块,或者是调用该线程调用wait后等待重新进入同步方法。

2 Thread.State NEW

Thread state for a thread which has not yet started.

线程创建未开始状态

3 Thread.State RUNNABLE

Thread state for a runnable thread. A thread in the runnable state is executing in the Java virtual machine but it may be waiting for other resources from the operating system such as processor.

线程运行状态,正在运行状态的线程正在被java虚拟机执行,但是也可能正在等待来自操作系统的其他资源例如处理器。

4 Thread.State TERMINATED

Thread state for a terminated thread. The thread has completed execution.

线程终止状态,这个线程被执行完成。

5 Thread.State TIMED_WAITING

Thread state for a waiting thread with a specified waiting time. A thread is in the timed waiting state due to calling one of the following methods with a specified positive waiting time:

Thread.sleep // sleep(long millis) or sleep(long millis, int nanos),The thread does not lose ownership of any monitors. 不会释放锁。

Object.wait with timeout

This method causes the current thread (call it T) to place itself in the wait set for this object and then to relinquish

any and all synchronization claims on this object.

这个方法会引起当前线程成为等待状态,并放弃这个对象上的同步的权益,就是释放了对象锁。

Thread.join with timeout

LockSupport.parkNanos

LockSupport.parkUntil

正在等待特定时间的线程状态,一个线程处在定时定时等待状态是因为调用了如下其中之一,带有明确的指定等待时间的方法

volatile 关键字的作用 保证该数据在多线程保持一致性。

如果使用volatile修饰变量,java代码编译后,运行指令会带有lock 前缀,jvm在处理这个lock信号时会引发两个操作

1 会将缓存数据写到主内存,lock前缀指令执行执行时 会锁住缓存区域,利用缓存一致性保证原子操作,并阻止多个处理器同时修改内存数据。

2 回写主内存的操作会使其他线程缓存的该内存地址的数据失效。

根据处理器的一致性协议,处理器会嗅探总线上的传播数据来检查自己缓存的数据是否是过期了,当处理器发现缓存地址失效,

会将缓存数据设置成失效,当处理这个数据时,从主内存中重新读取。

api 注释 join()方法

/*Waits at most {@code millis} milliseconds for this thread to

die. A timeout of {@code 0} means to wait forever.

*/

最多等待这个线程死亡多少毫秒,如果参数是0,则永远等待这个线程死亡

例 A线程正在运行,b线程对象join(args)

如果args == 0.则A线程一直等到B线程执行完成再执行

如果args >0 ,则A线程等待B线程执行args 毫秒时间后继续执行
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线程