1、建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC
首先使用Java多线程,使用Object.wait()和Object.notify()来对对象释放和唤醒操作。先创建三个对象锁a、b、c,每个打印线程需要获取前一个对象和自身对象才可以执行打印操作,否则等待。打印完后,立即释放自身对象及前一个对象,唤醒等待自身对象的线程。为了避免JVM调用线程的时间片轮转时间小于一个打印线程所需的时间,也就是说为了避免打印线程在还没来得及释放对象时,CPU写换到其他线程引起其他结果,在创建线程时,需让主线程sleep一下。

public class ABCThreadTest { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { Object a = new Object(); Object b = new Object(); Object c = new Object(); MyThreadPrinter pa = new MyThreadPrinter("A", c, a); MyThreadPrinter pb = new MyThreadPrinter("B", a, b); MyThreadPrinter pc = new MyThreadPrinter("C", b, c); new Thread(pa).start(); Thread.sleep(120); new Thread(pb).start(); Thread.sleep(120); new Thread(pc).start(); Thread.sleep(120); } } class MyThreadPrinter implements Runnable{ private String name; private Object prev; private Object self; MyThreadPrinter (String name, Object prev, Object self) { this.name = name; this.prev = prev; this.self = self; } @Override public void run() { int count = 10; while (count > 0) { synchronized (prev) { synchronized (self) { System.out.print(name); count--; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } self.notify(); } try { if(count>0) prev.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
2、建立一个线程,子线程循环5次,主线程循环10次,一共执行10次
在主线程main函数内新建一个子线程,执行Business中的sub方法,然后主线程执行Business中的main方法,sub方法与main方法通过变量bool实行同步。

//子线程循环5次,主线程循环10次,如此循环5次,好像是空中网的笔试题 public class ThreadCircle { public static void main(String[] args) { final Business business = new Business(); new Thread(new Runnable() { @Override public void run() { threadExecute(business, "sub"); } }).start(); threadExecute(business, "main"); } public static void threadExecute(Business business, String threadType) { for(int i = 0; i < 5; i++) { try { if("main".equals(threadType)) { business.main(i); } else { business.sub(i); } } catch (InterruptedException e) { e.printStackTrace(); } } } } class Business { private boolean bool = true; public synchronized void main(int loop) throws InterruptedException { while(bool) { this.wait(); } for(int i = 0; i < 10; i++) { System.out.println("main thread seq of " + i + ", loop of " + loop); } bool = true; this.notify(); } public synchronized void sub(int loop) throws InterruptedException { while(!bool) { this.wait(); } for(int i = 0; i < 5; i++) { System.out.println("sub thread seq of " + i + ", loop of " + loop); } bool = false; this.notify(); } } //此处wait时用while而不是用if,官方也推荐用while,因为在线程wait后,线程有可能被假唤醒,用while的话,假唤醒还会继续检测bool是否符合要求