public class MultiThread {
static Logger logger = LoggerFactory.getLogger(TestThread.class);
private int num = 0;
public synchronized void printNum(String tag) {
if (tag.equals("a")) {
num = 100;
logger.info("tag a set num over");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
num = 200;
logger.info("tag b set num over");
}
logger.info(String.format("tag %s num is %s", tag, num));
}
public static void main(String[] args) {
MultiThread m1 = new MultiThread();
MultiThread m2 = new MultiThread();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
m1.printNum("a");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
m2.printNum("b");
}
},"t2");
t1.start();
t2.start();
}
}
简单的类MultiThread中有一个方法printNum,根据不同的参数执行不同的赋值操作以及语句打印。
在main函数中,new了两个MultiThread对象,以及两个线程t1、t2分别执行printNum方法,参数为a和b。
虽然printNum中加了锁,但t1、t2的执行并不会相互干扰。因为它们的锁的级别是 对象级别锁 ,针对m1和m2各有一把锁。
10:31:20.226 [t1] INFO com.example.demo.sync.TestThread - tag a set num over
10:31:20.226 [t2] INFO com.example.demo.sync.TestThread - tag b set num over
10:31:20.237 [t2] INFO com.example.demo.sync.TestThread - tag b num is 200
10:31:21.235 [t1] INFO com.example.demo.sync.TestThread - tag a num is 100
但如果将printNum方法变为静态方法,那么锁的级别将会上升到 类级别锁 ,那么线程t1、t2想要执行printNum方法,必须等待对方释放锁资源。