62,621
社区成员
发帖
与我相关
我的任务
分享package com.test;
public class PlusThread extends Thread {
private static int j;
public static synchronized void Plus() {
j++;
System.out.println(Thread.currentThread().getName() + "-inc:" + j);
}
public void run() {
int n = 0;
while (n <= 100) {
Plus();
n++;
}
}
public static void main(String[] args) {
PlusThread.j = 0;
PlusThread thread1 = new PlusThread();
PlusThread thread2 = new PlusThread();
thread1.start();
thread2.start();
}
}
加上static后,这个方法就属于PlusThread类,而不是他的对象,也就是两个线程用的锁是PlusThread对应的类对象,而类对象只有一个啊,所以他们的锁是同一个,则能达到同步的效果。其实你你如果用synchronized 块来写的话,真接在类中定义一个静态成员对象,任意对象都行。。。。说白了想实现同步,就让各线程用的锁是同一个锁。。。。。。