Synchronized用法及基本原理
Synchronized能够修饰实例方法,类方法和代码块。注:sychronized不能修饰类以及类字段
- Synchronized修饰实例方法
public class SynchronizedClass {
static class Child extends Thread{
Counter counter;
Child(Counter counter){
this.counter=counter;
}
public void run() {
for(int i=0;i<100;++i) {
counter.incr();
}
}
}
public static void main(String[] args) throws InterruptedException {
Counter counter1=new Counter();
//创建100线程并发运行
Thread []threads=new Thread[100];
for(int i=0;i<100;++i) {
threads[i]=new Child(counter1);
threads[i].start();
}
//主线程等待子线程结束
for(int i=0;i<100;++i) {
threads[i].join();
}
System.out.println(counter1.getCount());
}
}
class Counter{
private int count=0;
public int getCount() {
return count;
}
//多个线程访问的方法需要使用synchronized
public synchronized void incr() {
count++;
}
}