java 死锁
程序员文章站
2022-06-22 09:39:37
class Ticket implements Runnable { private static int tick = 100; boolean flag = true; @Override public void run() { if (flag) { while (true) { synchr ......
class ticket implements runnable { private static int tick = 100; boolean flag = true; @override public void run() { if (flag) { while (true) { synchronized (integer.class) { show(); } } } else while (true) show(); } public synchronized void show() { synchronized (integer.class) { if (tick > 0) { try { thread.sleep(10); } catch (interruptedexception e) { } system.out.println(thread.currentthread().getname() + "...show():" + tick--); } } } } public class demo { public static void main(string[] args) { ticket t = new ticket(); thread t1 = new thread(t); thread t2 = new thread(t); t1.start(); try { thread.sleep(10); } catch (interruptedexception e) { } t.flag = false; t2.start(); } }
同步中嵌套同步。
写一个死锁:
class test implements runnable { private boolean flag; test(boolean flag) { this.flag = flag; } @override public void run() { if (flag) { while (true) { synchronized (object.class) { system.out.println("if object..."); synchronized (integer.class) { system.out.println("if integer..."); } } } } else { while (true) { synchronized (integer.class) { system.out.println("else integer..."); synchronized (object.class) { system.out.println("else object..."); } } } } } } public class deadlockdemo { public static void main(string[] args) { thread thread1 = new thread(new test(true)); thread thread2 = new thread(new test(false)); thread1.start(); thread2.start(); } }
上一篇: Linux 打包
下一篇: 手机QQ怎么开启热聊功能