1. synchronized function
用法: synchronized foo() {}
字面意思是让一个函数块保持同步,但是保持和谁同步呢? 答案是和另一个或一些加了synchronized 关键字的函数,它能保证在这个对象内,所有加synchronized 的函数在同一时间只有一个在运行,并只运行在某一个线程中,假如这些函数可能会被运行在不同的线程,又要同时访问同一个资源,那么就可以用它了。 (这段话不知道我说对了没有)Only one thread at a time can call a synchronized method for a particular object (although that thread can call more than one of the object’s synchronized methods). Objects can have synchronized methods that prevent threads from accessing that object until the synchronization lock is released。
例如 :
synchronized foo0() { A;}
synchronized foo1() { B;}
A, B 之间如果想同步,(即A执行时B不能执行,B执行时A不能执行),需要把两个函数都加上synchronized,只加一个相当于没加。
synchronized(syncObject) { // This code can be accessed // by only one thread at a time }
ArrayList lv = null; // Make a shallow copy of the List in case // someone adds a listener while we're // calling listeners: synchronized(this) { lv = (ArrayList)actionListeners.clone(); }
synchronized (object) {
...
try {
object.wait();
} catch(InterruptedException e) {
}
//object.notify();
...
}
synchronized void foo () {
...
try {
wait(); //Current thread wait();
} catch(InterruptedException e) {
}
//object.notify();
...
}注意catch线程中断的异常。
public void terminate() { stop = true; }
public void run() {
while (!stop) {
......
}
}// blocked is a thread
if(blocked == null) return; Thread remove = blocked; blocked = null; // to release it remove.interrupt();
本文深入探讨Java中的同步机制,包括synchronized关键字的功能与用法,如何通过对象锁创建临界区,以及同步方法与同步块的区别。此外还介绍了线程的基本状态及如何使用sleep和wait/notify实现线程间的同步。
1万+

被折叠的 条评论
为什么被折叠?



