雕刻时光

just do it……nothing impossible
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

共享内存的情况下,出现的高并发异常

Posted on 2016-06-04 15:52  huhuuu  阅读(1363)  评论(0编辑  收藏  举报
package thread;

public class TestShareMemory {

    
    static String shareM = "";
    static void alter(String tmp){
        shareM = tmp;
    }
    
    static class GThread extends Thread {
           public void run() {
                for (int i = 1; i < 2222122; i++){
                    alter("GThread");
                    if("XThread".equals(shareM)){
                    System.out.println("GThread:"+shareM);}
                }
                
            }
     }
     
     static class XThread extends Thread {
           public void run() {
                for (int i = 1; i < 2221222; i++){
                    alter("XThread");
                    if("GThread".equals(shareM)){
                    System.out.println("XThread:"+shareM);}
                }
                
            }
     }
     
    public static void main(String[] args) {

        Thread p2 = new XThread();
        Thread p1 = new GThread();
         p1.start();
         p2.start();   
    }

}

普通情况下,是不会出现“GThread:XThread” 这种情况的,但是在上述高并发,并且共享内存的情况下就可能出现问题!

 

可以通过这样加锁:

package thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestShareMemory {

    private static Lock lock = new ReentrantLock();
    static String shareM = "";

    static void alter(String tmp) {
        shareM = tmp;
    }

    static class GThread extends Thread {
        public void run() {
            for (int i = 1; i < 2222122; i++) {
                lock.lock();// 显示加锁
                try {
                    alter("GThread");
                    if ("XThread".equals(shareM)) {
                        System.out.println("GThread:" + shareM);
                    }
                } finally {
                    // 显示释放锁
                    lock.unlock();
                }

            }

        }
    }

    static class XThread extends Thread {
        public void run() {
            for (int i = 1; i < 2221222; i++) {
                lock.lock();// 显示加锁
                try {
                    alter("XThread");
                    if ("GThread".equals(shareM)) {
                        System.out.println("XThread:" + shareM);
                    }
                } finally {
                    // 显示释放锁
                    lock.unlock();
                }
            }

        }
    }

    public static void main(String[] args) {

        Thread p2 = new XThread();
        Thread p1 = new GThread();
        p1.start();
        p2.start();
    }

}

 

总结:在高并发并且有共享内存的情况下,有几个方法解决并发问题:

1、把共享内存的变量变成线程内部的变量。(有时候是没必要线程共享变量)。

2、在必要线程共享变量的时候,对涉及到的读写共享变量的地方加锁。