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 从数据角度分析

  1. ThreadLocal 变量
    ThreadLocal只解决线程安全的问题 并不是用来解决线程同步的,
    所以它与锁可以说是没有什么关系的。
    有人这样描述:ThreadLocal解决的是同一个线程内的资源共享问题
    如果您想为一个类的所有实例维持一个变量的实例,将会用到静态类成员变量。
    类 --》 对象 (多个对象共享同一个静态类成员变量)
    如果您想以线程为单位维持一个变量的实例,将会用到线程局部变量
    线程1 --》线程1cpu运行时间段 (同一个线程的多个cpu运行时间段共享同一个ThreadLocal 变量)
  2. 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

基于线程池

转载于:https://www.cnblogs.com/NoviceOnRoad/p/4874916.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值