线程礼让
package com.threadpriority.ljb;
public class ThreadComity {public static void main(String[] args) {MyThread01 my1 = new MyThread01();MyThread01 my2 = new MyThread01();Thread t1 = new Thread(my1,"线程1");Thread t2 = new Thread(my2,"线程2");t1.start();t2.start();}
}
class MyThread01 implements Runnable{&#64;Overridepublic void run() {for (int i &#61; 0; i < 5; i&#43;&#43;) {System.out.println(Thread.currentThread().getName() &#43; "->" &#43; i);if (i &#61;&#61; 3) {System.out.println(Thread.currentThread().getName() &#43; "礼让");Thread.currentThread().yield();}}}}
死锁
package com.threadpriority.ljb;
public class ThreadDeadlock {public static void main(String[] args) throws InterruptedException {TestThreadDeadlock my &#61; new TestThreadDeadlock();my.name &#61; "张三";new Thread(my).start();Thread.sleep(100);my.name &#61; "李四";new Thread(my).start();}
}
package com.threadpriority.ljb;public class TestThreadDeadlock implements Runnable{Object bowl &#61; new Object();Object spoon &#61; new Object();String name;&#64;Overridepublic void run() {if(name.equals("张三")) {synchronized (bowl) {System.out.println("张三拿到bowl&#xff0c;去拿spoon");try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}synchronized (spoon) {System.out.println("张三拿到spoon,|去拿bowl");}}}else if(name.equals("李四")) {synchronized (spoon) {System.out.println("李四拿到spoon&#xff0c;去拿bowl");try {Thread.sleep(300);} catch (InterruptedException e) {e.printStackTrace();}synchronized (bowl) {System.out.println("李四拿到bowl,|去拿spoon");}}}}}