路人过河

package victors; import java.util.Random; public class Test { public static void main(String[] args) { // TODO 自动生成的方法存根Guoddong guoddong = new Guoddong(); // Thread thread = new Thread(); Random random = new Random(); String str = "abcdefghijklmnopqrstuvwxyz"; for (int i = 1; i <= 10; i++) { Thread thread = new Thread(guoddong); String itemStr = "" + str.charAt(random.nextInt(str.length())) + str.charAt(random.nextInt(str.length())) + str.charAt(random.nextInt(str.length())) + str.charAt(random.nextInt(str.length())) + i; // 随机生成四个 thread.setName("线程" + i + ":路人" + itemStr); thread.start(); } }}


package victors; public class Guoddong implements Runnable { private Object lock = new Object(); @Override public void run() { // TODO 自动生成的方法存根 synchronized (lock) { System.out.println(Thread.currentThread().getName() + "正在通过山洞"); try { Thread.sleep(2000); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "通过山洞"); } } }


路人过河
文章图片

    推荐阅读