这是一个经典java面试题目,主要考察线程之间如何实现资源共享以及同步。
package com.bookshop.util;
public class Test {
private int j = 100;
public static void main(String args[]) {
Test tt = new Test();
Inc inc = tt.new Inc();
Dec dec = tt.new Dec();
for (int i = 0; i < 1000; i++) {// 外层用来跑1000次
for (int j = 0; j < 2; j++) {// 内层用来生成四个线程
Thread t = new Thread(inc);
t.start();
Thread t1 = new Thread(dec);
t1.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() {
inc();
}
}
class Dec implements Runnable {
public void run() {
dec();
}
}
}