package testng;
import java.util.HashMap;
import java.util.Hashtable;
public class ThreadSynchronized {
//全局变量,多线程同时操作,会出现脏读,写问题
private static int a=0;
private static final String lock="";
private static void threadTest() {
for (int i = 0; i < 10; i++) {
new Thread() {
public void run() {
//资源互斥
synchronized (ThreadSynchronized.class) {
a++;
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("plus:" + Thread.currentThread().getName() + ": " + a);
}
}
}.start();
}
}
public static void main(String[] args) {
threadTest();
}
}
输出结果:
plus:Thread-0: 1
plus:Thread-9: 2
plus:Thread-7: 3
plus:Thread-8: 4
plus:Thread-6: 5
plus:Thread-5: 6
plus:Thread-4: 7
plus:Thread-3: 8
plus:Thread-2: 9
plus:Thread-1: 10