我这里是对加一和减一分别用两个方法inc(),dec()进行了封装,并且在方法前加了synchronized关键字,已达到线程同步的效果,测试是用匿名内部类的方式实现了四个线程,分别调用加方法和减方法,达到两个线程对j加一和两个线程对j减一的效果
package com.briup.freestyle; public class TestThread { private static int j; public static void main(String[] args) { Thread t1 = new Thread("加线程1") { public void run() { for(int i = 0;i < 10;i++){ inc(); } } }; Thread t2= new Thread("加线程2") { public void run() { for(int i = 0;i < 10;i++){ inc(); } } }; Thread t3= new Thread("减线程3") { public void run() { for(int i = 0;i < 10;i++){ dec(); } } }; Thread t4= new Thread("减线程4") { public void run() { for(int i = 0;i < 10;i++){ dec(); } } }; //启动四个线程 t1.start(); t2.start(); t3.start(); t4.start(); } //加1方法 public synchronized static void inc() { j++; System.out.println("inc:"+Thread.currentThread().getName()+":"+j); } //减1方法 public synchronized static void dec() { j--; System.out.println("dec:"+Thread.currentThread().getName()+":"+j); } }测试结果:多次测试发现线程是同步的
