synchronized 用于多线程安全,保证有使用synchronized修饰的方法,在多线程下只能在同一时刻保证一个线程调用。
那么在一个类中有两个方法使用了synchronized关键字修饰,那么表现如何呢?我会在下面进行一个演示,在文章结尾会给出一结论。
假设,我们一个类中有两个方法test1和test2
一、test1和test2都为静态方法
package test;
public class Test03 {
public static synchronized void test1() {
int i = 5;
while (i-- > 0) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "i:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static synchronized void test2() {
int i = 5;
while (i-- > 0) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "i:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
Test03.test1();
}
},"test1()");
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
Test03.test2();
}
},"test2()");
t1.start();
t2.start();
}
}
运行结果:
二、test1和test2都为非静态方法
package test;
public class Test03 {
public synchronized void test1() {
int i = 5;
while (i-- > 0) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "i:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void test2() {
int i = 5;
while (i-- > 0) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "i:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test03 t = new Test03();
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
t.test1();
}
},"test1()");
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
t.test2();
}
},"test2()");
t1.start();
t2.start();
}
}
运行结果:
三、test1静态方法,test2为非静态方法
package test;
public class Test03 {
public synchronized void test1() {
int i = 5;
while (i-- > 0) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "i:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static synchronized void test2() {
int i = 5;
while (i-- > 0) {
try {
Thread.sleep(500);
System.out.println(Thread.currentThread().getName() + "i:" + i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test03 t = new Test03();
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
t.test1();
}
},"test1()");
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
t.test2();
}
},"test2()");
t1.start();
t2.start();
}
}
运行结果:
综上结果,我们可以分析出以下结果:
什么是互斥性:事件A与事件B在任何一次试验中都不会同时发生,则称事件A与事件B互斥。
1.当两个或两个以上的方法都为非静态方法时,synchronized 修饰的方法具有互斥性。
2.当两个或两个以上的方法都为静态方法时,synchronized 修饰的方法具有互斥性。
3.当两个或两个以上的方法中有静态又同时有非静态方法,synchronized 修饰的方法不具有互斥性。