| |
wait()/notify() 通常,多线程之间需要协调工作。例如,浏览器的一个显示图片的线程displaythread想要执行显示图片的任务,必须等待下载线程downloadthread将该图片下载完毕。如果图片还没有下载完,displaythread可以暂停,当downloadthread完成了任务后,再通知displaythread“图片准备完毕,可以显示了”,这时,displaythread继续执行。 以上逻辑简单的说就是:如果条件不满足,则等待。当条件满足时,等待该条件的线程将被唤醒。在java中,这个机制的实现依赖于wait/notify。等待机制与锁机制是密切关联的。例如: synchronized(obj) { while(!condition) { obj.wait(); } obj.dosomething(); } 当线程a获得了obj锁后,发现条件condition不满足,无法继续下一处理,于是线程a就wait()。 在另一线程b中,如果b更改了某些条件,使得线程a的condition条件满足了,就可以唤醒线程a: synchronized(obj) { condition = true; obj.notify(); } 需要注意的概念是: # 调用obj的wait(), notify()方法前,必须获得obj锁,也就是必须写在synchronized(obj) {...} 代码段内。 # 调用obj.wait()后,线程a就释放了obj的锁,否则线程b无法获得obj锁,也就无法在synchronized(obj) {...} 代码段内唤醒a。 # 当obj.wait()方法返回后,线程a需要再次获得obj锁,才能继续执行。 # 如果a1,a2,a3都在obj.wait(),则b调用obj.notify()只能唤醒a1,a2,a3中的一个(具体哪一个由jvm决定)。 # obj.notifyall()则能全部唤醒a1,a2,a3,但是要继续执行obj.wait()的下一条语句,必须获得obj锁,因此,a1,a2,a3只有一个有机会获得锁继续执行,例如a1,其余的需要等待a1释放obj锁之后才能继续执行。 # 当b调用obj.notify/notifyall的时候,b正持有obj锁,因此,a1,a2,a3虽被唤醒,但是仍无法获得obj锁。直到b退出synchronized块,释放obj锁后,a1,a2,a3中的一个才有机会获得锁继续执行。 wait()/sleep()的区别 前面讲了wait/notify机制,thread还有一个sleep()静态方法,它也能使线程暂停一段时间。sleep与wait的不同点是:sleep并不释放锁,并且sleep的暂停和wait暂停是不一样的。obj.wait会使线程进入obj对象的等待集合中并等待唤醒。 但是wait()和sleep()都可以通过interrupt()方法打断线程的暂停状态,从而使线程立刻抛出interruptedexception。 如果线程a希望立即结束线程b,则可以对线程b对应的thread实例调用interrupt方法。如果此刻线程b正在wait/sleep/join,则线程b会立刻抛出interruptedexception,在catch() {} 中直接return即可安全地结束线程。 需要注意的是,interruptedexception是线程自己从内部抛出的,并不是interrupt()方法抛出的。对某一线程调用interrupt()时,如果该线程正在执行普通的代码,那么该线程根本就不会抛出interruptedexception。但是,一旦该线程进入到wait()/sleep()/join()后,就会立刻抛出interruptedexception。 guardedsuspention guardedsuspention模式主要思想是: 当条件不满足时,线程等待,直到条件满足时,等待该条件的线程被唤醒。 我们设计一个客户端线程和一个服务器线程,客户端线程不断发送请求给服务器线程,服务器线程不断处理请求。当请求队列为空时,服务器线程就必须等待,直到客户端发送了请求。 先定义一个请求队列:queue package com.crackj2ee.thread; import java.util.*; public class queue { private list queue = new linkedlist(); public synchronized request getrequest() { while(queue.size()==0) { try { this.wait(); } catch(interruptedexception ie) { return null; } } return (request)queue.remove(0); } public synchronized void putrequest(request request) { queue.add(request); this.notifyall(); } } 蓝色部分就是服务器线程的等待条件,而客户端线程在放入了一个request后,就使服务器线程等待条件满足,于是唤醒服务器线程。 客户端线程:clientthread package com.crackj2ee.thread; public class clientthread extends thread { private queue queue; private string clientname; public clientthread(queue queue, string clientname) { this.queue = queue; this.clientname = clientname; } public string tostring() { return "[clientthread-" + clientname + "]"; } public void run() { for(int i=0; i<100; i++) { request request = new request("" + (long)(math.random()*10000)); system.out.println(this + " send request: " + request); queue.putrequest(request); try { thread.sleep((long)(math.random() * 10000 + 1000)); } catch(interruptedexception ie) { } } system.out.println(this + " shutdown."); } } 服务器线程:serverthread package com.crackj2ee.thread; public class serverthread extends thread { private boolean stop = false; private queue queue; public serverthread(queue queue) { this.queue = queue; } public void shutdown() { stop = true; this.interrupt(); try { this.join(); } catch(interruptedexception ie) {} } public void run() { while(!stop) { request request = queue.getrequest(); system.out.println("[serverthread] handle request: " + request); try { thread.sleep(2000); } catch(interruptedexception ie) {} } system.out.println("[serverthread] shutdown."); } } 服务器线程在红色部分可能会阻塞,也就是说,queue.getrequest是一个阻塞方法。这和java标准库的许多io方法类似。 最后,写一个main来启动他们: package com.crackj2ee.thread; public class main { public static void main(string[] args) { queue queue = new queue(); serverthread server = new serverthread(queue); server.start(); clientthread[] clients = new clientthread[5]; for(int i=0; i<clients.length; i++) { clients[i] = new clientthread(queue, ""+i); clients[i].start(); } try { thread.sleep(100000); } catch(interruptedexception ie) {} server.shutdown(); } } 我们启动了5个客户端线程和一个服务器线程,运行结果如下: [clientthread-0] send request: request-4984 [serverthread] handle request: request-4984 [clientthread-1] send request: request-2020 [clientthread-2] send request: request-8980 [clientthread-3] send request: request-5044 [clientthread-4] send request: request-548 [clientthread-4] send request: request-6832 [serverthread] handle request: request-2020 [serverthread] handle request: request-8980 [serverthread] handle request: request-5044 [serverthread] handle request: request-548 [clientthread-4] send request: request-1681 [clientthread-0] send request: request-7859 [clientthread-3] send request: request-3926 [serverthread] handle request: request-6832 [clientthread-2] send request: request-9906 ...... 可以观察到serverthread处理来自不同客户端的请求。 思考 q: 服务器线程的wait条件while(queue.size()==0)能否换成if(queue.size()==0)? a: 在这个例子中可以,因为服务器线程只有一个。但是,如果服务器线程有多个(例如web应用程序有多个线程处理并发请求,这非常普遍),就会造成严重问题。 q: 能否用sleep(1000)代替wait()? a: 绝对不可以。sleep()不会释放锁,因此sleep期间别的线程根本没有办法调用getrequest()和putrequest(),导致所有相关线程都被阻塞。 q: (request)queue.remove(0)可以放到synchronized() {}块外面吗? a: 不可以。因为while()是测试queue,remove()是使用queue,两者是一个原子操作,不能放在synchronized外面。 总结 多线程设计看似简单,实际上必须非常仔细地考虑各种锁定/同步的条件,稍不小心,就可能
|
|