如何写出线程安全的程序的思考

1)使用线程安全的Vector进行操作,多线程并发的情况下,一定是线程安全的吗?

答案:不是

原因:虽然Vector的大部分方法都加上了synchronized同步块,但是比如如下需求:

void deleteLastEle(){

  int lastIndex = vec.size() - 1;  // 1

   vec.remove(lastIndex);        // 2

}

虽然1和2处都是线程安全的,但是在多线程环境下,1 2联合在一起并不是原子操作,不是线程安全的,多线程下导致索引异常。

Run.java

package VectorTest;

import java.util.Random;
import java.util.Vector;

public class Run implements Runnable {
    private Vector v = new Vector();

    private Random r = new Random();

    public void init() {
        for (int i = 0; i < 10; i++) {
            v.add(i);
        }
    }

    private void deleteLast() {
        int lastIndex = v.size() - 1;

        if (lastIndex >= 0) {
            System.out.println(lastIndex);
            v.remove(lastIndex);
        }
    }

    @Override
    public void run() {
        deleteLast();
    }
}

Main.java

package VectorTest;

public class Main {
    public static void main(String[] args) {
        Run r = new Run();
        r.init();

        for (int i = 0; i < 100; i++) {
            new Thread(r).start();
        }
    }
}

/*
 9
 8
 8
 7
 7
 6
 5
 4
 3
 2
 1
 0
 Exception in thread "Thread-5" Exception in thread "Thread-15" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 8
 at java.util.Vector.remove(Vector.java:831)
 at VectorTest.Run.deleteLast(Run.java:22)
 at VectorTest.Run.run(Run.java:28)
 at java.lang.Thread.run(Thread.java:748)
 java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 7
 at java.util.Vector.remove(Vector.java:831)
 at VectorTest.Run.deleteLast(Run.java:22)
 at VectorTest.Run.run(Run.java:28)
 at java.lang.Thread.run(Thread.java:748)
 */

因此还是要下面这样写才行:

    private void deleteLast() {
        // 为了原子性,必须加上锁
        synchronized (v) {
            int lastIndex = v.size() - 1;
            if (lastIndex >= 0) {
                System.out.println(lastIndex);
                v.remove(lastIndex);
            }
        }
    }
这样Main下面才能正确执行
/*
9
8
7
6
5
4
3
2
1
0
*/

这样保证只能有一个线程执行,才行。

2)如何保证netty在有业务线程池的情况下,保证线程的安全?

以最常见的房间类的服务器为例子.

RoomMgr.java

Netty线程模型:

a1

a2     EventLoop1

a3

...

b1

b2     EventLoop2

b3

...

c1

c2    EventLoop3

c3

...

a1 a2 a3发往消息始终是在EventLoop1上, 对应Thread1

b1 b2 b3发往消息始终是在EventLoop2上,对应Thread2

c1 c2 c3发往消息始终是在EventLoop3上,对应Thread3

假设:当前a1  b1  c1 3个人在一个房间内斗地主,考虑这么一个业务需求,:

当房间满3人开始游戏,由于RoomMgr房间管理对象中管理一个个Room,那么3个人反复加入和退出房间,那么由于3个人在3个线程,因此3个线程对Room的访问是有并发访问的问题,

如果不加锁, Room在判断当前房间的人数 room.size()可能会有bug,因此需要对Room加锁才能保证访问正确

发布了1620 篇原创文章 · 获赞 144 · 访问量 179万+

猜你喜欢

转载自blog.csdn.net/themagickeyjianan/article/details/104885224