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、在必要线程共享变量的时候,对涉及到的读写共享变量的地方加锁。
时间: 2024-11-05 22:17:10