有三个线程名字分别是A、B、C,每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次
一个比较简单的例子
对公共资源加锁,以阻塞其它线程。
用一个全局变量(3个线程都可访问的公共变量)控制状态
/** * 有三个线程名字分别是A、B、C,每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次 * * @author chenhening * @date 2017年3月16日 */ public class MyABC extends Thread { private static Object o = new Object();// 对象锁,必须是static private static int count = 0;// 控制输出哪个字母 private char ID;// 字母 private int id;// 字母对应的数字 private int num = 0;// 打印次数 public MyABC(int id, char ID) { this.id = id; this.ID = ID; } @Override public void run() { synchronized (o) { while (num < 10) { if (count % 3 == id) { System.out.print(ID); ++count; ++num; // 唤醒所有等待线程 o.notifyAll(); } else { try { // 如果不满足条件,则阻塞等待 o.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { (new MyABC(0, 'A')).start(); (new MyABC(1, 'B')).start(); (new MyABC(2, 'C')).start(); } }
第二种方法:
/** * 有三个线程名字分别是A、B、C,每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次 * * @author chenhening * @date 2017年3月16日 */ public class SwitchStatus extends Thread { private static String currentThread = "A";// 初始为A private static Object lock = new Object();// 作为锁 private String name = ""; private int count = 10;// 打印次数 public SwitchStatus(String name) { this.name = name; } @Override public void run() { while (count > 0) { synchronized (lock) { if (currentThread.equals(this.name)) { System.out.print(name); count--; if (currentThread.equals("A")) { currentThread = "B"; } else if (currentThread.equals("B")) { currentThread = "C"; } else if (currentThread.equals("C")) { currentThread = "A"; System.out.println(); } } } } } public static void main(String[] args) { (new SwitchStatus("A")).start(); (new SwitchStatus("B")).start(); (new SwitchStatus("C")).start(); } }
第三种:
/** * 有三个线程名字分别是A、B、C,每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次 * * @author chenhening * @date 2017年3月16日 */ public class SleepExample extends Thread { private static int currentCount = 0; public SleepExample(String name) { // 设置线程的名称 this.setName(name); } @Override public void run() { while (currentCount < 30) {// 10遍*3个字母 switch (currentCount % 3) {// 除以3求余数 case 0: if ("A".equals(getName())) { System.out.print(getName()); currentCount++; } break; case 1: if ("B".equals(getName())) { System.out.print(getName()); currentCount++; } break; case 2: if ("C".equals(getName())) { System.out.print(getName()); currentCount++; } break; } } } public static void main(String[] args) { // 线程启动顺序无关 new SleepExample("A").start(); new SleepExample("B").start(); new SleepExample("C").start(); } }

浙公网安备 33010602011771号