java线程相关
java线程相关
java
线程
1 线程的状态
This is an example of UML protocol state machine diagram showing thread states and thread life cycle for the Thread class in Java 6.
Thread is a lightweight process, the smallest unit of scheduled execution. Instance of the Thread class in Java 6 could be in one of the following states:
new,
runnable,
timed waiting,
waiting,
blocked,
terminated.
These states are Java Virtual Machine (JVM) states reported by JVM to Java programs. At any given point in time thread could be in only one state.
Protocol state machine example - Thread states and life cycle in Java 6
New is the thread state for a thread which was created but has not yet started.
At the lower operating system (OS) level, JVM's runnable state could be considered as a composite state with two substates. When a thread transitions to the runnable JVM state, the thread first goes into the ready substate. Thread scheduling decides when the thread could actually start, proceed or be suspended. Thread.yield() is explicit recommendation to thread scheduler to pause the currently executing thread to allow some other thread to execute.
A thread in the runnable state is executing from the JVM point of view but in fact it may be waiting for some resources from the operating system.
Timed waiting is a thread state for a thread waiting 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(sleeptime)
Object.wait(timeout)
Thread.join(timeout)
LockSupport.parkNanos(timeout)
LockSupport.parkUntil(timeout)
A thread is in the waiting state due to the calling one of the following methods without timeout:
Object.wait()
Thread.join()
LockSupport.park()
Note, that thread in the waiting state is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate. It means that waiting state could be made a composite state with states corresponding to these specific conditions.
Thread is in the blocked state while waiting for the monitor lock to enter a synchronized block or method or to reenter a synchronized block or method after calling Object.wait().
A synchronized statement or method acquires a mutual-exclusion lock on behalf of the executing thread, executes a block or method, and then releases the lock. While the executing thread owns the lock, no other thread may acquire the lock and is blocked waiting for the lock.
After thread has completed execution of run() method, it is moved into terminated state.
java.lang.Thread 1.0
• static void sleep(long millis)
sleeps for the given number of milliseconds.
• Thread(Runnable target)
constructs a new thread that calls the run() method of the specified target.
• void start()
starts this thread, causing the run() method to be called. This method
will return immediately. The new thread runs concurrently.
• void run()
calls the run method of the associated Runnable. 。。
• void interrupt()
sends an interrupt request to a thread. The interrupted status of the
thread is set to true. If the thread is currently blocked by a call to
sleep, then an InterruptedException is thrown.
• static boolean interrupted()
tests whether the current thread (that is, the thread that is executing
this instruction) has been interrupted. Note that this is a static method.
The call has a side effect—it resets the interrupted status of the current
thread to false.
• boolean isInterrupted()
tests whether a thread has been interrupted. Unlike the static
interrupted method, this call does not change the interrupted status of
the thread.
• static Thread currentThread()
returns the Thread object representing the currently executing thread.
• void join()
waits for the specified thread to terminate.
• void join(long millis)
waits for the specified thread to die or for the specified number of milliseconds to pass.
• Thread.State getState() 5.0
gets the state of this thread; one of NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED.
• void stop()
stops the thread. This method is deprecated.
• void suspend()
suspends this thread's execution. This method is deprecated.
• void resume()
resumes this thread. This method is only valid after suspend() has been
invoked. This method is deprecated.
java.lang.Runnable 1.0
• void run()
must be overriden and supplied with instructions for the task that you
want to have executed.
2 多线程实现方式
2.1 直接继承thread
class Demo extend thread //直接就是线程类
{
public void run() {
..... ; //线程的任务(job task 算法)
}
}
Demo d1 = new Demo();
Demo d2 = new Demo();
d1.start();
d2.start();
2.2 实现runnable接口
class Demo extend parent implents Runable //线程类的任务封装类
{
public void run(){
.... ; //线程的任务(job task 算法)
}
}
Demo d = new Demo();
Thread t1 = new Thread(d);
Thread t2 = new Thread(d);
Demo d1 = new Demo();
Demo d2 = new Demo();
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
d1.start();
d2.start();
2.3 Callable、Future和FutureTask
http://www.cnblogs.com/dolphin0520/p/3949310.html
前两种在执行完任务之后无法获取执行结果。
Callable类似Runnable
public interface Runnable {
//由于run()方法返回值为void类型,所以在执行完任务之后无法返回任何结果。
public abstract void run();
}
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
* call()函数返回的类型就是传递进来的V类型。
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
Future就是对于具体的Runnable或者Callable任务的执行结果进行取消、查询是否完成、获取结果
public interface Future<V> {
}
public interface RunnableFuture<V> extends Runnable, Future<V> {
void run();
}
public class FutureTask<V> implements RunnableFuture<V>
可以看出RunnableFuture继承了Runnable接口和Future接口.
而FutureTask实现了RunnableFuture接口.
所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值.
3 线程并发
http://www.uml-diagrams.org/java-7-concurrent-uml-class-diagram-example.html
3.1 分析方法
谁支持有锁(线程)
锁所在的对象(对象)
锁的类型(读写)
3.2 从数据角度分析
- ThreadLocal 变量
ThreadLocal只解决线程安全的问题 并不是用来解决线程同步的,
所以它与锁可以说是没有什么关系的。
有人这样描述:ThreadLocal解决的是同一个线程内的资源共享问题
如果您想为一个类的所有实例维持一个变量的实例,将会用到静态类成员变量。
类 --》 对象 (多个对象共享同一个静态类成员变量)
如果您想以线程为单位维持一个变量的实例,将会用到线程局部变量
线程1 --》线程1cpu运行时间段 (同一个线程的多个cpu运行时间段共享同一个ThreadLocal 变量) - volatile 变量
为了提高性能,Java 语言规范允许 JRE 在引用变量的每个线程中维护该变量的一个本地副本。您可以将变量的这些 "线程局部" 副本看作是与缓存类似,在每次线程需要访问变量的值时帮助它避免检查主存储器。
当写一个volatile变量时,JMM会把该线程对应的本地内存中的共享变量刷新到主内存。当读一个volatile变量时,JMM会把该线程对应的本地内存置为无效。线程接下来将从主内存中读取共享变量。
从内存语义的角度来说,volatile与监视器锁有相同的效果:
volatile写和监视器的释放有相同的内存语义;
volatile读与监视器的获取有相同的内存语义。
http://www.ibm.com/developerworks/cn/java/j-5things15/
http://www.infoq.com/cn/articles/java-memory-model-4/
3.2 从算法角度分析
3.2.1 通用锁 更细更灵活
class Demo
{
private Object lock = new Object();
public void method()
{
synchronized (lock){
code_block
}
}
}
3.2.2 intrinsic lock or monitor lock 内在锁 监视器
class Demo
{
/*以下三种等价*/
public synchronized void method()
{
method_body
}
public void method()
{
this.intrinsicLock.lock();
try {
method_body
}
finally{
this.intrinsicLock.unlock();
}
}
public void method()
{
synchronized (this /*lockObject=this*/ ){
method_body
}
}
}
3.2.3 ReentrantLock 可重如锁
public void method() //JDK5 **显示锁**
{
Lock lock = new ReentrantLock();
lock.lock();
try{
//code block (method body)
}
finally{
lock.unlock();
}
}
4 线程池
线程池的类体系结构. 包含Callable Futrure, ScheduleThreadPoolExecutor
http://blog.csdn.net/vernonzheng/article/details/8299108
http://jingyan.baidu.com/article/0320e2c1e9666e1b87507b8d.html
http://www.cnblogs.com/dolphin0520/p/3932921.html
http://www.cnblogs.com/coser/archive/2012/03/10/2389264.html
5 调度器
5.1 是Timer和TimerTask
一个Timer为一个单独的线程,虽然一个Timer可以调度多个TimerTask,
但是对于一个Timer来讲是串行的
5.2 ScheduleThreadPoolExecutor
基于线程池
java线程相关的更多相关文章
- Java线程相关的热门面试题
---恢复内容开始--- 下面是Java线程相关的热门面试题,你可以用它来好好准备面试. 1) 什么是线程? 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序 ...
- java线程相关基本方法
java线程中常用的基本方法有wait,notify,notifyAll,sleep,join,yield等. 线程的生命周期一共分为五个部分,分别是:新建(New).就绪(Runnable).运行( ...
- Java线程和进程相关面试题与答案总结
有几天没有写一写博客了,今天就带给大家一些面试题和参考答案吧! 这些都是上海尚学堂Java培训的学员去面试时遇到的问题,今天总结出来的是Java线程相关类的面试题.把参考答案和解析也发布出来,供大家学 ...
- 【转载】 Java线程面试题 Top 50
Java线程面试题 Top 50 不管你是新程序员还是老手,你一定在面试中遇到过有关线程的问题.Java语言一个重要的特点就是内置了对并发的支持,让Java大受企业和程序员 的欢迎.大多数待遇丰厚的J ...
- Java线程面试题 Top 50 (转载)
转载自:http://www.cnblogs.com/dolphin0520/p/3958019.html 原文链接:http://www.importnew.com/12773.html 本文由 ...
- 50 道 Java 线程面试题(转载自牛客网)
下面是 Java 线程相关的热门面试题,你可以用它来好好准备面试. 1) 什么是线程? 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序员可以通过它进行多处理 ...
- Java线程面试题 Top 50
转自:http://www.importnew.com/12773.html 不管你是新程序员还是老手,你一定在面试中遇到过有关线程的问题.Java语言一个重要的特点就是内置了对并发的支持,让Java ...
- 【多线程】Java线程面试题 Top 50(转载)
Java线程面试题 Top 50 原文链接:http://www.importnew.com/12773.html 本文由 ImportNew - 李 广 翻译自 javarevisited.欢迎 ...
- Java线程面试题 Top 50(转载)
原文链接:http://www.importnew.com/12773.html 本文由 ImportNew - 李 广 翻译自 javarevisited.欢迎加入Java小组.转载请参见文章末尾的 ...
随机推荐
- SQL查询和删除重复字段的内容
--例如: id NAME VALUE 1 a pp 2 a pp 3 b iii 4 b pp 5 b pp 6 c pp 7 c pp 8 c iii --id是主键 --要求得到这样的结果 id ...
- UWP 手绘视频创作工具技术分享系列 - 位图的绘制
前面我们针对 SVG 的解析和绘制做了介绍,SVG 是图片的一种形式,而另一种很重要的图片是:位图,包括 png.jpeg.bmp 等格式.位图的基本规则是,组成的基本元素是像素点,由宽度 * 高度个 ...
- vs重装找不到 $(WindowsSdkDir) 配置问题
vs重装的一个bug,找了一个下午,删了再装vs也没用. 在配置表 HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SDKs ...
- Python格式化字符串--format
format格式化字符串方法相较于老版%格式方法的优点: 1.不需要理会数据类型的问题,在%方法中'%s'只能替代字符串类型. 2.单个参数可以多次输出,参数顺序可以不相同. 3.填充方式十分灵活,对 ...
- php中get_headers函数的作用及用法的详细介绍
get_headers() 是PHP系统级函数,他返回一个包含有服务器响应一个 HTTP 请求所发送的标头的数组.如果失败则返回 FALSE 并发出一条 E_WARNING 级别的错误信息(可用来判断 ...
- 开源的JavaScript插件化框架MinimaJS
本文介绍我开发的一个JavaScript编写的插件化框架——MinimaJS,完全开源,源码下载地址:https://github.com/lorry2018/minimajs.该框架参考OSGi规范 ...
- .NET程序集引用COM组件MSScriptControl所遇到的问题
问题描述:为了在C#中执行js脚本,在一个目标平台编译为Any Cpu的.NET程序集中引用了MSScriptControl组件,在winform程序中,调用这个程序集中的执行js的方法,没有任何问题 ...
- Spring事务的传播行为和隔离级别
事物注解方式: @Transactional [一]传播行为: 使用方法:@Transactional(propagation=Propagation.REQUIRED) Require:支持当前事务 ...
- DB---数据库中Schema的理解
今天看到了Schema一词,对于它的理解网上也是说法很多,有一种受到认可的程度比较大,暂且先使用一下: " 首先我来做一个比喻,什么是Database,什么是Schema,什么是Table, ...
- Elasticsearch 索引别名与Template
在使用elasticsearch的时候,经常会遇到需要淘汰掉历史数据的场景. 为了方便数据淘汰,并使得数据管理更加灵活,我们经常会以时间为粒度建立索引,例如: 每个月建立一个索引:monthly-20 ...