多线程不安全演示,线程越多,现象越明显,这边只启了四个线程。
package com.example.demo;import java.util.LinkedList;
import java.util.UUID;public class LInkedListThread {public static void main(String[] args) {final LinkedList<String> linkedList = new LinkedList();for (int i = 0; i < 4; i++) {new Thread(new Runnable() {@Overridepublic void run() {linkedList.add(UUID.randomUUID().toString().substring(0,10));System.out.println(linkedList);}}).start();}}
}
结果如下图,没有写入四个,因为在现场运行过程中多个线程可能会抢占到相同的地址。
解决方案1:
使用synchronized锁:
package com.example.demo;import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;public class LInkedListThread {public static void main(String[] args) {final LinkedList<String> linkedList = new LinkedList();Collection ts = Collections.synchronizedCollection(linkedList);for (int i = 0; i < 4; i++) {new Thread(new Runnable() {public void run() {linkedList.add(UUID.randomUUID().toString().substring(0,10));System.out.println(linkedList);}}).start();}}
}
效果如下:
解决方案2:
使用ConcurrentLinkedQueue:cas(无锁化机制)加volatile 关键字来解决
package com.example.demo;import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;public class LInkedListThread {public static void main(String[] args) {final ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue(); // cas 无锁化机制 volatile 关键字来解决的for (int i = 0; i < 4; i++) {new Thread(new Runnable() {public void run() {concurrentLinkedQueue.add(UUID.randomUUID().toString().substring(0,10));System.out.println(concurrentLinkedQueue);}}).start();}}
}
现象如下: