Java多线程基础学习(二)

百科知识2025-04-261

以上述代码为例,如果加了关键字synchronized,则一个线程在使用共享资源o时,另一个线程必须等到前一个线程使用完,才能使用。

加synchronized的输出结果:

而不加synchronized的输出结果:

10. 容器类并发问题的同步解决方法

JDK中提供了并发容器,可以直接帮我们解决容器类出现的并发问题。它们大部分都存在java.util.concurrent这个包中,包括:ConcurrentHashmap,CopyOnWriteArrayList,ConcurrentLinkedQueue,BlockingQueue,ConcurrentSkipListMap。下面是使用ConcurrentHashmap解决Map容器并发问题的例子:

package threadStudy;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ThreadConcurrencyCollectionTest {

 public static void main(String[] args) {
     Thread thread1 = new Thread(new HashTest.AddThread(0), "T0");
     Thread thread2 = new Thread(new HashTest.AddThread(1), "T1");
     thread1.start();
     thread2.start();

 }

}

class HashTest{
//static Map<String, String> map = new HashMap<String, String>();
static Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());
public static class AddThread extends Thread{
private int start;
public AddThread(int start){
this.start = start;
}
public void run(){
for (int i=start; i<10000; i+=2){
System.out.println(Integer.toString(i));
map.put(Integer.toString(i), Integer.toBinaryString(i));
}
}

 }

}