package threadStudy;
public class ThreadSynchronizedTest {
public static void main(String[] args) throws InterruptedException{
int i=0;
ObjA o = new ObjA(i);
TheThread theThread1 = new TheThread(o);
TheThread theThread2 = new TheThread(o);
theThread1.start();
theThread2.start();
}
static class TheThread extends Thread{
private ObjA objA;
public TheThread(ObjA objA){
this.objA = objA;
}
public void run(){
objA.method();
}
}
static class ObjA{
int i;
public ObjA(int i){
this.i = i;
}
synchronized public void method(){
for (int j=0;j<10;j++){
i++;
System.out.println(Thread.currentThread().getName()+ ": " + i);
try{
Thread.sleep(200);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
以上述代码为例,如果加了关键字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 www.gsm-guard.net;
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
map = new HashMap();
static Map map = Collections.synchronizedMap(new HashMap());
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));
}
}
}
}
-->