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小组.转载请参见文章末尾的 ...
随机推荐
- 启用事务操作,解决批量插入或更新sqlite,mssql等数据库耗时问题
private void button1_Click(object sender, EventArgs e) { //Sqlite使用事务批量操作 极大的提高速度 DateTime starttime ...
- 【转载】WAI-ARIA无障碍网页应用属性完全展示
文章转载自 张鑫旭-鑫空间-鑫生活 http://www.zhangxinxu.com/wordpress/ 原文链接:http://www.zhangxinxu.com/wordpress/?p=2 ...
- mysql登录出现1045错误修改方法
在cmd中输入mysql -uroot -p出现1045错误如下: ERROR 1045(28000): Access denied for user 'root'@'localhost'(using ...
- 深入浅出Diffie–Hellman
一.作者 这个密钥交换方法,由惠特菲尔德·迪菲(Bailey Whitfield Diffie).马丁·赫尔曼(Martin Edward Hellman)于1976年发表. 二.说明 它是一种安全协 ...
- 吾八哥学Python(四):了解Python基础语法(下)
咱们接着上篇的语法学习,继续了解学习Python基础语法. 数据类型大体上把Python中的数据类型分为如下几类:Number(数字),String(字符串).List(列表).Dictionary( ...
- ELK系列~对fluentd参数的理解
这段时候一直在研究ELK框架,主要集成在对fluentd和nxlog的研究上,国内文章不多,主要看了一下官方的API,配合自己的理解,总结了一下,希望可以帮到刚入行的朋友们! Fluentd(日志收集 ...
- Linux系统fdisk分区
以下操作全部基于win7 64位系统上的Linux虚拟机(CentOS6.6). 当Linux虚拟机的硬盘空间不够用时,可以手动添加硬盘块,流程如下: 右键虚拟机,点击“Add”按钮: 选择“Hard ...
- xmanager 打开centos7图形化窗口
centos7 最小化安装后,个别时候需要执行一些带图形界面的命令.比如安装oracle,打开xclock等. 前置条件:centos7系统 ,xmanager 已安装 用xclock做测试 1.因为 ...
- [IR] Concept Search and LDA
重要的是通过实践更深入地了解贝叶斯思想,先浅浅地了解下LDA. From: http://blog.csdn.net/huagong_adu/article/details/7937616/ 传统方法 ...
- python 模块的概念介绍
模块 模块:本质就是一个.py文件分为三部分:内置模块.第三方模块,自定义模块 模块: 顶层文件 python模块python模块可以将代码量较大的程序分割成多个有组织的.彼此独立但又能互相交互的代码 ...