1:项目结构
2:代码
ThreadDemo类
package tianyi.demo5;
public class ThreadDemo {
private int i=88;
class Increase implements Runnable {
private synchronized void inc() {
i++;
System.out.println(Thread.currentThread().getName() + " 加1 " +"i="+ i);
}
public void run() {
inc();
}
}
class Decrease implements Runnable {
private synchronized void dec() {
i--;
System.out.println(Thread.currentThread().getName() + " 减1 "+"i=" + i);
}
public void run() {
dec();
}
}
public static void main(String[] args) {
ThreadDemo t = new ThreadDemo();
Increase increase = t.new Increase();
Decrease decrease = t.new Decrease();
//Thread thread = null;
for (int i = 0; i < 2; i++) {
new Thread(increase).start();
new Thread(decrease).start();
}
}
}
3:效果展示