【Synchronized】1.synchronized同步线程安全锁
package test.thread;
//两个线程操作add方法,实现对count的增加,一个线程增加十次。
public class SyncronizedTest {
public static void main(String[] args) {
//这里两个线程,不再引用同一个counter实例.counterA和counterB的add方法同步在他们所属的对象上。调用counterA的add方法将不会阻塞调用counterB的add方法。
Counter counterA = new Counter();
Counter counterB = new Counter();
new Thread(new SafeThread(counterA)).start();
new Thread(new SafeThread(counterB)).start();
}
}class Counter{
//add
long count = 0;
public synchronized long add(long num) {
//静态方法中不能调用非静态属性
this.count += num;
return count;
}
}
class SafeThread implements Runnable{
protected Counter counter = null;
SafeThread(Counter counter){
this.counter = counter;
}public void run() {
for(int i=0;
i<10;
i++) {
long fin = counter.add(1);
System.out.println(i + "=>" + fin);
}
}
}