/**
* 这段代码是关于多线程中同步方法调用的一些总结:
*
* 1.如果调用的是普通方法,就和普通程序一样执行,有时候这样在多线程中会出错,是我们所不愿意看到的。
* 2.如果调用的是同步的方法,则调用对象会被加锁,因此不能访问该对象的synchronized方法,直至锁被释放。
* 3.如果调用的是静态同步方法,则静态方法所属类的Class对象会被加锁,因此不能访问该类的静态synchronized方法,直至锁被释放。
*
* 为了验证如上规则,请分别将下面程序解注释,验证结果。
*/
class MyObject{
// 2. public static synchronized void execute01(){
// 1. public void execute01(){
public synchronized void execute01(){
for(int i = 0; i < 20; ++i){
try {
System.out.println("Hello : " + i);
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// 2. public static synchronized void execute02(){
// 1. public void execute02(){
public synchronized void execute02(){
for(int i = 0; i < 20; ++i){
try{
System.out.println("World : " + i);
Thread.sleep(500);
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Thread01 extends Thread{
private MyObject obj;
public Thread01(MyObject obj){
this.obj = obj;
}
@Override
public void run() {
obj.execute02();
}
}
class Thread02 extends Thread{
private MyObject obj;
public Thread02(MyObject obj){
this.obj = obj;
}
@Override
public void run() {
obj.execute01();
}
}
public class SynchronizedTest {
public static void main(String[] args) {
MyObject obj = new MyObject();
Thread thread01 = new Thread01(obj);
Thread thread02 = new Thread02(obj);
thread01.start();
thread02.start();
}
}
多线程中方法调用
最新推荐文章于 2024-04-29 09:35:28 发布