方法一:
HomeWork1.java
public class HomeWork1 { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { synchronized ("a"){ System.out.println(Thread.currentThread().getName()+"get lock a"); synchronized ("b"){ System.out.println(Thread.currentThread().getName()+"get lock b"); } System.out.println(Thread.currentThread().getName()+"free lock b"); } System.out.println(Thread.currentThread().getName()+"free lock a"); } }).start(); new Thread(new Runnable() { @Override public void run() { synchronized ("b"){ System.out.println(Thread.currentThread().getName()+"get lock b"); synchronized ("a"){ System.out.println(Thread.currentThread().getName()+"get lock a"); } System.out.println(Thread.currentThread().getName()+"free lock a"); } System.out.println(Thread.currentThread().getName()+"free lock b"); } }).start(); } }
方法二:
VolatileDemo.java
public class VolatileDemo { static boolean flag = false; public static void main(String[] args) throws InterruptedException { new Thread(new Runnable() { @Override public void run() { while (true) { if (flag) { System.out.println("break"); break; } } } }).start(); Thread.sleep(1000); flag = true; } }