
线程间通信:使用类锁和对象锁的区别
现有场景:一台多线程打印机需要被两个线程操作。以下代码使用类锁和对象锁分别实现线程通信:
public class threadtalk { public static void main(string[] args) { printer_1 printer = new printer_1(); thread t1 = new thread(printer); thread t2 = new thread(printer); t1.setname("线程一"); t2.setname("线程二"); t1.start(); t2.start(); }}class printer_1 implements runnable { // 使用对象锁 private int number = 0; @override public void run() { while (true) { synchronized (this) { notify(); if (number <= 100) { system.out.println(thread.currentthread().getname() + "打印数字:" + number); number++; try { wait(); } catch (interruptedexception e) { e.printstacktrace(); } } else { break; } } } }}
使用对象锁(synchronized (this))时,正常运行。然而,如果将对象锁换成类锁(synchronized (printer_1.class)),代码会报错:
java.lang.illegalmonitorstateexception:...at java.lang.object.notify(native method)at test2.printer_1.run(threadtalk.java:26)...
为何会有这样的区别?
微信 WeLM
WeLM不是一个直接的对话机器人,而是一个补全用户输入信息的生成模型。
33 查看详情
当使用类锁时,实际上锁的是整个printer_1类。此时,该类的所有实例都共享同一个锁。而在代码中,使用了实例对象的wait()和notify()方法,这与类锁的控制不同,导致违反了锁的使用规范,引发了illegalmonitorstateexception异常。
正确的做法是将类锁用于控制类相关的操作,例如类的静态方法或变量的访问。而实例对象相关的操作,应该使用对象锁。修改后的代码如下:
class Printer_1 implements Runnable { // 使用对象锁 private int number = 0; @Override public void run() { while (true) { synchronized (this) { notify(); if (number <= 100) { System.out.println(Thread.currentThread().getName() + "打印数字:" + number); number++; try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } else { break; } } } }}
以上就是使用类锁和对象锁进行线程通信的区别是什么?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/451816.html
微信扫一扫
支付宝扫一扫