Java Concurrency 1:Basic

来源:互联网 发布:方齐禾的淘宝店是什么 编辑:程序博客网 时间:2024/06/07 07:17

基本概念

程序、进程、线程
程序是指令、数据及其组织形式的描述。现代操作系统在运行一个程序时,会为其创建一个进程。例如启动一个Java程序就会创建一个Java进程,用jps指令可以查看所有的Java进程。
现代操作系统调度的最小单元是线程,也叫轻量级进程,一个进程里可以创建多个线程,进程是线程的容器。

Java中线程实现方式有两种:
1. 直接继承Thread类(Thread类也是实现了Runnable接口);
2. 先实现Runnable接口,然后将类传给Thread执行;
实际应用采取该方式:
① 避免由于Java的单继承特性带来的局限;
② 将任务机制和执行机制分离开,属于比较好的设计;

开启线程前设置好线程的名称,方便后续用jstack之类的工具分析,养成良好的规范意识。

线程间通信

线程的几个状态,在Thread类中有枚举:

  • new
  • runnable
    java线程将就绪和运行两种状态笼统的称作runnable
  • blocked
  • waiting
  • timed-waiting
  • terminated

如下是源码:

   public enum State {        /**         * Thread state for a thread which has not yet started.         */        NEW,        /**         * 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.         */        RUNNABLE,        /**         * 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         * {@link Object#wait() Object.wait}.         */        BLOCKED,        /**         * Thread state for a waiting thread.         * A thread is in the waiting state due to calling one of the         * following methods:         * 
    *
  • {@link Object#wait() Object.wait} with no timeout
  • *
  • {@link #join() Thread.join} with no timeout
  • *
  • {@link LockSupport#park() LockSupport.park}
  • *
* *

A 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. */ 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: *

    *
  • {@link #sleep Thread.sleep}
  • *
  • {@link Object#wait(long) Object.wait} with timeout
  • *
  • {@link #join(long) Thread.join} with timeout
  • *
  • {@link LockSupport#parkNanos LockSupport.parkNanos}
  • *
  • {@link LockSupport#parkUntil LockSupport.parkUntil}
  • *
*/ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATED; }


java状态变迁

Java线程状态变迁


由该图可以看出有些方法是属于根类Object的,有些是属于Thread类的。
执行Thread.sleep(long)和Object.wait(long)方法后都会进入TIMED_WAIT状态,但是sleep()方法不会释放锁,而wait会让出锁,具体源码中都有说明,一看便知。
这里线程终止是等待run()方法执行完成后自动进入TERMINATED状态,那有没有什么方式可以停止线程呢?已经被标记为deprecated的stop()方法自然不能再用,因为该方法会造成多线程下的数据不一致性问题。
书中给出两种比较“优雅”的方式来停止线程。

public class Shutdown {    public static void main(String[] args) throws Exception {        Runner one = new Runner();        Thread countThread = new Thread(one, "CountThread");        countThread.start();        // 睡眠1秒,main线程对CountThread进行中断,使CountThread能够感知中断而结束        TimeUnit.SECONDS.sleep(1);        countThread.interrupt();        Runner two = new Runner();        countThread = new Thread(two, "CountThread");        countThread.start();        // 睡眠1秒,main线程对Runner two进行取消,使CountThread能够感知on为false而结束        TimeUnit.SECONDS.sleep(1);        two.cancel();    }    private static class Runner implements Runnable {        private long             i;     /**         *  这里用volatile是要保证可见性吗         */        private volatile boolean on = true;        @Override        public void run() {            while (on && !Thread.currentThread().isInterrupted()) {                i++;            }            System.out.println("Count i = " + i);        }        public void cancel() {            on = false;        }    }}

参考:
http://www.cnblogs.com/freemanabc/p/5618159.html
http://www.importnew.com/16142.html
《Java并发编程的艺术》