62,614
社区成员
发帖
与我相关
我的任务
分享
public class ThreadTest {
private int j;
public static void main(String args[]) {
ThreadTest tt = new ThreadTest();
Inc inc = tt.new Inc();
Dec dec = tt.new Dec();
for (int i = 0; i < 2; i++) {
Thread t = new Thread(inc);
t.start();
t = new Thread(dec);
t.start();
}
}
private synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "-inc:" + j);
}
private synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "-dec:" + j);
}
class Inc implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
inc();
}
}
}
class Dec implements Runnable {
public void run() {
for (int i = 0; i < 100; i++) {
dec();
}
}
}
}
private synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "-inc:" + j);
}
等价于:
private void inc() {
synchronized(this){
j++;
System.out.println(Thread.currentThread().getName() + "-inc:" + j);
}
}
也就是说,是锁定tt对象
public synchronized void xxxx() {
aaaa;
bbbb;
cccc;
}
与
public void xxxx() {
synchronized(this) {
aaaa;
bbbb;
cccc;
}
}