public class ThreadTest1 {
private int j;
public static void main(String args[]) {
ThreadTest1 tt = new ThreadTest1();
Inc inc = tt.new Inc();
Dec dec = tt.new Dec();
for (int i = 0; i < 2; i++) {//设计线程,4个线程设计成2个部分,两个加,两个减,线程随即开启 Thread t; 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 {//定义类继承Runnable接口
public void run() { for (int i = 0; i < 100; i++) { inc(); } } }
class Dec implements Runnable {//定义类继承Runnable接口
public void run() { for (int i = 0; i < 100; i++) { dec(); } } }
}