Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SynchronizedTest 4个线程 2个加一,2个减一
package test;
public class SynchronizedTest {
public static void main(String[] args) {
J j = new J();
Thread inc1 = new Thread(new IncrementThread(j), "inc1");
Thread inc2 = new Thread(new IncrementThread(j), "inc2");
Thread dec1 = new Thread(new DecrementThread(j), "dec1");
Thread dec2 = new Thread(new DecrementThread(j), "dec2");
inc1.start();
inc2.start();
dec1.start();
dec2.start();
}
}
class J {
private int j;
public synchronized void inc() {
j++;
System.out.println(Thread.currentThread().getName() + "=== after add ,j is " + j);
}
public synchronized void dec() {
j--;
System.out.println(Thread.currentThread().getName() + "=== after dec ,j is " + j);
}
}
class IncrementThread implements Runnable {
private J j;
public IncrementThread(J j) {
this.j = j;
}
@Override
public void run() {
j.inc();
}
}
class DecrementThread implements Runnable {
private J j;
public DecrementThread(J j) {
this.j = j;
}
@Override
public void run() {
j.dec();
}
}
class AA {
public synchronized void method1(){
}
}
class B extends AA{
@Override
public synchronized void method1() {
// synchronized关键字是不能继承的 必须显示定义
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.