阅读量:0
Exercise
创建三个线程:一个线程打印 100个A,一个线程打印 100 个 B ,一个线程打印 100个C 输出效果:ABC ABC ABC…交替打印
package com.kane.exercise01; public class PrintABC implements Runnable { private static final Object lock = new Object(); private static int state = 0; private String str; private int num; public PrintABC(String str, int num) { this.str = str; this.num = num; } @Override public void run() { for (int i = 0; i < 100; i++) { synchronized (lock) { while (state % 3 != num) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(str); state++; lock.notifyAll(); // 唤醒其他线程 } if(state%3 == 0) { System.out.println(""); } } } }
package com.kane.exercise01; public class Demo1 { public static void main(String[] args) { Thread t1 = new Thread(new PrintABC("A",0)); Thread t2 = new Thread(new PrintABC("B",1)); Thread t3 = new Thread(new PrintABC("C",2)); t1.start(); t2.start(); t3.start(); } }
编写两个线程,一个 线程打印1-52,另一个线程打印字母A-Z打印顺序是12A34B…,即按照整数和字母的顺序从小到大打印,并且每打印两个整数后,打印一个字母,交替循环打印
package com.kane.exercise02; import java.util.concurrent.Semaphore; public class Demo { private static final Semaphore Numbersemaphore = new Semaphore(1); private static final Semaphore Dansemaphore = new Semaphore(0); public static void main(String[] args) { Thread t1 = new Thread(new NumberPrint()); Thread t2 = new Thread(new DanPrint()); t1.start(); t2.start(); } static class NumberPrint implements Runnable { @Override public void run() { for (int i = 1; i < 53; i++) { try { Numbersemaphore.acquire(); System.out.print(i + " "); if (i%2== 0) { Dansemaphore.release(); } else { Numbersemaphore.release(); } } catch (InterruptedException e) { throw new RuntimeException(e); } } } } static class DanPrint implements Runnable { @Override public void run() { for (char c = 'A'; c <= 'Z'; c++) { try { Dansemaphore.acquire(); System.out.print(c); System.out.println(""); Numbersemaphore.release(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } } }