多线程资源竞争 --交叉打印数字和字母
package com.java.main.test.thread; public class TestThread { public static Object object = new Object(); public static void main(String[] args) { //TestThread testThread = new TestThread(); //new Thread(new CharThread(testThread)).start(); //new Thread(new NumThread(testThread)).start(); new Thread(new PrintChar()).start(); new Thread(new PrintNum()).start(); } /*public static void main(String[] args) { // TODO Auto-generated method stub ExecutorService service = Executors.newFixedThreadPool(2); service.execute(new Runnable() { @Override public void run() { // TODO Auto-generated method stub int i = 0; for (; i < 26; i++) { System.out.print(i); Thread.yield(); } } }); service.execute(new Runnable() { char[] cs = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; @Override public void run() { // TODO Auto-generated method stub int i = 0; for (; i < 26; i++) { System.out.print(cs[i]); Thread.yield(); } } }); } */ static class PrintChar implements Runnable{ public void printChar(){ for (int i = 'a'; i <= 'z'; i++) { synchronized(object){ System.out.print((char)i); object.notifyAll(); try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } @Override public void run() { printChar(); } } static class PrintNum implements Runnable{ public void printNum(){ for (int i = 0; i <= 26; i++) { synchronized(object){ System.out.print(i+1); object.notifyAll(); try { object.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } @Override public void run() { printNum(); } } }