java多線程 synchronized volatile Atomic LOCK的使用

來源:互聯網
上載者:User

java中可以使用 synchronized volatile Atomic  LOCK進行多線程編程來實現安全執行緒。現對這幾種方式進行示範與總結。


其中:


1. 單純使用volatile是沒有辦法保證安全執行緒的

2. 使用synchronized和 lock要注意使用方法,要在主進程中建立lock對象的執行個體或定義synchronized方法

3. 使用Atomic  原子類也是可以保證安全執行緒的。


/**    * @Package   * @Description  * @author chenj * @date 2015-9-14 下午11:09:40  * @version V1.0    */import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** *  * @author chenj| 2015-01-01 * */public class TestMultiThread{Object _object = new Object();static int i=0;static Integer si = 0;static volatile Integer vi = 0;static AtomicInteger autoInteger = new AtomicInteger();static int synClassInt = 0;static int lockInt = 0;static int staticClassInt = 0;static Lock lock = new ReentrantLock();static Object _obj = new Object();public void testVolatileInteger(Thread _thread1,Thread _thread2) throws Exception{        ExecutorService pool = Executors.newCachedThreadPool();        //建立實現了Runnable介面對象,Thread對象當然也實現了Runnable介面        Thread t1 = _thread1;        Thread t2 = _thread2;        //將線程放入池中進行執行        pool.execute(t1);        pool.execute(t2);        //關閉線程池        pool.shutdown();        while(true){              if(pool.isTerminated()){              if(staticClassInt!=0){                System.out.println("所有的子線程都結束了。"); System.out.println("i>>>>>"+i);System.out.println("vi>>>>>"+vi);System.out.println("si>>>>>"+si);System.out.println("autoInteger>>>>>"+autoInteger);System.out.println("synClassInt>>>>>"+synClassInt);System.out.println("lockInt>>>>>"+lockInt);System.out.println("staticClassInt>>>>>"+staticClassInt);            }                break;              }           }  }public synchronized static void testSychronizedMethod() {i++;}static class testSychronizedMethodClass extends Thread{@Override    public void run() {    for(int k=0;k<200000;k++){    testValue();    }    }    public static void testValue() {    staticClassInt++ ;    }}   public static void main(String[] args) throws Exception{TestMultiThread testMultiThread = new TestMultiThread();testMultiThread.testVolatileInteger(new ThreadSychronizedMethead(),new ThreadSychronizedMethead());Thread.sleep(100);testMultiThread.testVolatileInteger(new ThreadStaticInteger(),new ThreadStaticInteger());Thread.sleep(100);testMultiThread.testVolatileInteger(new ThreadStaticVolatileInteger(),new ThreadStaticVolatileInteger());Thread.sleep(100);testMultiThread.testVolatileInteger(new ThreadAtomicInteger(),new ThreadAtomicInteger());Thread.sleep(100);testMultiThread.testVolatileInteger(new ThreadSychronizedObjMethead(),new ThreadSychronizedObjMethead());Thread.sleep(100);testMultiThread.testVolatileInteger(new ThreadLock(),new ThreadLock());Thread.sleep(100);testMultiThread.testVolatileInteger(new TestMultiThread.testSychronizedMethodClass(),new TestMultiThread.testSychronizedMethodClass());Thread.sleep(100);}}class ThreadStaticVolatileInteger extends Thread {    @Override    public void run() {    for(int k=0;k<200000;k++){    TestMultiThread.vi++;    }    }}class ThreadAtomicInteger extends Thread {    @Override    public void run() {    for(int k=0;k<200000;k++){    TestMultiThread.autoInteger.incrementAndGet();    }    }}class ThreadStaticInteger extends Thread {    @Override    public void run() {    for(int k=0;k<200000;k++){    TestMultiThread.si++;    }    }}class ThreadSychronizedMethead extends Thread {    @Override    public void run() {    for(int k=0;k<200000;k++){    TestMultiThread.testSychronizedMethod();    }    }        public synchronized void test() {TestMultiThread.i++;}}class ThreadSychronizedObjMethead extends Thread {    @Override    public void run() {    for(int k=0;k<200000;k++){    synchronized(TestMultiThread._obj){    TestMultiThread.synClassInt++;    }    }    }}class ThreadLock extends Thread {    @Override    public void run() {    for(int k=0;k<200000;k++){    lockObj();    }    }        public void lockObj(){    TestMultiThread.lock.lock();try{TestMultiThread.lockInt ++;}finally{TestMultiThread.lock.unlock();}}}

程式運行結果:

所有的子線程都結束了。
i>>>>>400000
vi>>>>>257432
si>>>>>222170
autoInteger>>>>>400000
synClassInt>>>>>400000
lockInt>>>>>400000
staticClassInt>>>>>266997



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.