Java 语言提供两个基本的同步机制:synchronized 方法(synchronized methods )和 synchronized 语句(synchronized statements)。
示例先大概说一下 Java Synchronized 关键字,当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻只有一个线程执行该段代码。
如下代码所示:
package cn.db.syncdemo;
public class NewClass {/**
* 同步方法
*/
public void synchronizedMethod() { synchronized (this) {int i = 5;
while (i-- > 0) {System.out.PRintln(Thread.currentThread().getName() + " : " + i
+ " synchronized method");
try {Thread.sleep(2000);
} catch (InterruptedException e) {System.out.println(e.toString());
}
}
}
}
/**
* 同步方法 2
*/
public void synchronizedMethod2() { synchronized (this) {int i = 5;
while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i
+ " synchronized method 2");
try {Thread.sleep(1000);
} catch (InterruptedException e) {System.out.println(e.toString());
}
}
}
}
/**
* 非同步方法
*/
public void nonSynchronizedMethod() {int i = 5;
while (i-- > 0) {System.out.println(Thread.currentThread().getName() + " : " + i
+ " nonSynchronized method");
try {Thread.sleep(1000);
} catch (InterruptedException e) {System.out.println(e.toString());
}
}
}
public static void main(String[] args) {final NewClass mClass = new NewClass();
// t1 和 t2 都要访问同一个同步方法 synchronizedMethod
Thread t1 = new Thread(new Runnable() { public void run() {mClass.synchronizedMethod();
}
}, "Thread 1");
Thread t2 = new Thread(new Runnable() { public void run() {mClass.synchronizedMethod();
}
}, "Thread 2");
// t3 要访问另一个同步方法 synchronizedMethod2
Thread t3 = new Thread(new Runnable() { public void run() {mClass.synchronizedMethod2();
}
新闻热点
疑难解答