java写一个死锁

分手后的思念是犯贱 2022-08-13 12:37 242阅读 0赞
  1. package thread.deadlock;
  2. /**
  3. * 一个死锁
  4. * @author zzh
  5. *
  6. */
  7. public class DeadLock {
  8. public static void main(String[] args) {
  9. Test test = new Test(true);
  10. Test test_2 = new Test(false);
  11. Thread t1 = new Thread(test);
  12. Thread t2 = new Thread(test_2);
  13. t1.start();
  14. t2.start();
  15. }
  16. }
  17. class MyLock{
  18. public static final Object locka = new Object();
  19. public static final Object lockb = new Object();
  20. }
  21. class Test implements Runnable{
  22. private boolean flag;
  23. Test(boolean flag){
  24. this.flag = flag;
  25. }
  26. @Override
  27. public void run() {
  28. if(flag){
  29. while (true) {
  30. synchronized (MyLock.locka) {
  31. System.out.println("if......locka...");
  32. synchronized (MyLock.lockb) {
  33. System.out.println("if......lockb...");
  34. }
  35. }
  36. }
  37. }else{
  38. while (true) {
  39. synchronized (MyLock.lockb) {
  40. System.out.println("else......lockb...");
  41. synchronized (MyLock.locka) {
  42. System.out.println("else......locka...");
  43. }
  44. }
  45. }
  46. }
  47. }
  48. }

发表评论

表情:
评论列表 (有 0 条评论,242人围观)

还没有评论,来说两句吧...

相关阅读