public Runnable run1 = new Runnable(){
8. public void run() {
9. synchronized(this) { //设置关键字 synchronized,以当前类为锁
10. while(count < 1000) {
11. try {
12. //打印是否执行该方法
13. System.out.println(Thread.currentThread().getName() + " run1: "+count++);
14. } catch (Exception e) {
15. e.printStackTrace();
16. }
17. }
18. }
19. }};
20. public Runnable run2 = new Runnable(){
21. public void run() {
22. synchronized(this) {
23. while(count < 1000) {
24. try {
25. System.out.println(Thread.currentThread().getName()
26. + " run2: "+count++);
27. } catch (Exception e) {
28. e.printStackTrace();
29. }
30. }
31. }
32. }};
33. public static void main(String[] args) throws InterruptedException {
34. qq t = new qq(); //创建一个对象
35. new Thread(t.run1).start(); //获取该对象的方法 1
36. new Thread(t.run2).start(); //获取该对象的方法 2
37. }
synchronized方式死锁
最新推荐文章于 2025-07-04 13:04:22 发布