JavaAndroid知识Java学习笔记

Java并发之并行程序基础

2016-11-18  本文已影响167人  辣公公

实战Java高并发程序设计笔记


有关线程你必须知道的事

  1. 进程
    • 进程(Process)是计算机中程序关于某数据集合上的一次运行活动,事系统进行资源分配和调度的基本单位,是操作系统结构的基础。
  2. 线程的几个状态
/**
     * A representation of a thread's state. A given thread may only be in one
     * state at a time.
     */
    public enum State {
        /**
         * The thread has been created, but has never been started.
         */
        NEW,
        /**
         * The thread may be run.
         */
        RUNNABLE,
        /**
         * The thread is blocked and waiting for a lock.
         */
        BLOCKED,
        /**
         * The thread is waiting.
         */
        WAITING,
        /**
         * The thread is waiting for a specified amount of time.
         */
        TIMED_WAITING,
        /**
         * The thread has been terminated.
         */
        TERMINATED
    }
  1. Thread的start( )方法和run( )方法的区别

    • run( )方法是一个普通的方法,调用该方法会在当前线程中串行执行run( )中的代码
    • start( )是个一个线程安全的方法,该方法首先会检查当前线程是否处于New状态, 然后将其加入到ThreadGroup中,最后调用Native start0( )方法,在新的线程中串行执行run( )中的代码
  2. 终止线程

public class ThreadStop {
    public static void main(String arg[]) throws InterruptedException {
        Thread mThread = new StopThread() ;
        mThread.start();
        Thread.sleep(100);
        mThread.stop();//调用stop终止线程可导致run( )方法中的代码仅执行一部分
    }
static class StopThread extends Thread {
        @Override
        public void run() {
            for (int i = 0; i < 100000; i++) {
                    System.out.println("i "+ i);
            }
        }
    }
}

可能得到如下结果,i的值并不等于99999
i 24956
i 24957
i 24958
i 24959
i 24960
i 24961
i 24962

  1. 线程中断
 public void interrupt() {
        if (this != Thread.currentThread())
            checkAccess();
        synchronized (blockerLock) {
            Interruptible b = blocker;
            if (b != null) {
                interrupt0();           // Just to set the interrupt flag
                b.interrupt(this);
                return;
            }
        }
        interrupt0();  
    }
public boolean isInterrupted() {
        return isInterrupted(false);
    }

    /**
     * Tests if some Thread has been interrupted.  The interrupted state
     * is reset or not based on the value of ClearInterrupted that is
     * passed.
     */
    private native boolean isInterrupted(boolean ClearInterrupted);
/**
     * Tests whether the current thread has been interrupted.  The
     * <i>interrupted status</i> of the thread is cleared by this method.  In
     * other words, if this method were to be called twice in succession, the
     * second call would return false (unless the current thread were
     * interrupted again, after the first call had cleared its interrupted
     * status and before the second call had examined it).
     *
     * <p>A thread interruption ignored because a thread was not alive
     * at the time of the interrupt will be reflected by this method
     * returning false.
     *
     * @return  <code>true</code> if the current thread has been interrupted;
     *          <code>false</code> otherwise.
     * @see #isInterrupted()
     * @revised 6.0
     */
    public static boolean interrupted() {
        return currentThread().isInterrupted(true);
    }
public class ThreadInterrupt {
    public static void main(String args[]) throws InterruptedException {
        Thread thread = new InterruptThread();
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
        Thread.sleep(4000);
    }
    static class InterruptThread extends Thread {
        @Override
        public void run() {
            while (true) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("Interrupted");
                    break;
                }
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    System.out.println("Interrupted when sleep");
                    e.printStackTrace();
                    Thread.currentThread().interrupt();
                }
                Thread.yield();//让出当前CPU,然后跟其他线程竞争CPU的使用权
            }
        }
    }
}
  1. 等待( wait )和通知( notify )
public final native void wait() throws InterruptedException;
public final native void notify();
public final native void notifyAll();
  1. 挂起( suspend ) 和继续执行( resume )线程
  1. 等待线程结束( join ) 和谦让( yield )
public final void join() throws InterruptedException
public final synchronized void join(long millis)
public static native void yield();
上一篇 下一篇

猜你喜欢

热点阅读