Created
March 4, 2013 17:22
-
-
Save doubledouble/5083872 to your computer and use it in GitHub Desktop.
SynchronizedTest 4个线程 2个加一,2个减一
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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