/**
* All rights Reserved, Designed By jakie
* @author: jakie
* @date: 2018年11月11日
* @version V1.0
* @Copyright: jakie. All rights reserved.
* 注意:仅供大家学习参考
*/
package testMQ;
/**
*
* @author jakie
*
*/
public class ThreadTest {
/**
* 测试方法1
*/
public synchronized void test1() {
try {
int i = 5;
while (i-- > 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
Thread.sleep(500);
}
} catch (Exception e) {
}
}
/**
* 测试方法2
*/
public synchronized void test2() {
try {
int i = 5;
while (i-- > 0) {
System.out.println(Thread.currentThread().getName() + ":" + i);
Thread.sleep(500);
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
ThreadTest tt = new ThreadTest();
//测试线程1
Thread test1 = new Thread(new Runnable() {
@Override
public void run() {
tt.test1();
}
}, "test1");
//测试线程2
Thread test2 = new Thread(new Runnable() {
@Override
public void run() {
tt.test2();
}
}, "test2");
test1.start();
test2.start();
}
}
在本例子中,两个方法都使用了synchronized,但是两个方法相当于两把锁,在main方法中是主线程是顺序执行,所以最后的执行结果如下,有0的情况是因为边界值1>0进入while循环