首先给出题目要求
甲线程输出:A、B、C、D、E
乙线程输出:1、2、3、4、5
丙线程数出:甲、乙、丙、丁、戊
最终输出结果为(注:这是唯一可能的结果)
A 1 甲 B 2 乙 C 3 丙 D 4 丁 E 5 戊
无非都是同步,消费者生产者的例子比较好,实现方法也是各有不同,这里自己整理了两种方法,做个笔记。
方法一代码
- package com.liuyanzhao;
- /*
- *
- * @author WellsLiu
- *
- */
- class MySignal {
- int data = 0;
- }
- class MyThread implements Runnable {
- MySignal s = new MySignal();
- char c[];
- int runFlag;
- int nextFlag;
- public MyThread(MySignal s, char[] c, int x, int y) {
- this.s = s;
- this.c = c;
- runFlag = x;
- nextFlag = y;
- }
- public void run() {
- synchronized (s) {
- for (int i = 0; i < c.length; i++) {
- while (s.data != runFlag) {
- try {
- s.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c[i] + ” “);
- s.data = nextFlag;
- s.notifyAll();
- }
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- MySignal s = new MySignal();
- char[] c1 = { ‘A’, ‘B’, ‘C’, ‘D’, ‘E’ };
- char[] c2 = { ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘ };
- char[] c3 = { ‘甲’, ‘乙’, ‘丙’, ‘丁’, ‘戊’ };
- Thread t1 = new Thread(new MyThread(s, c1, 0, 1));
- Thread t2 = new Thread(new MyThread(s, c2, 1, 2));
- Thread t3 = new Thread(new MyThread(s, c3, 2, 0));
- t1.start();
- t2.start();
- t3.start();
- }
- }
方法二代码
- package com.liuyanzhao;
- /*
- *
- * @author WellsLiu
- *
- */
- class Resource {
- int flag=1;
- }
- class Thread1 extends Thread {
- Resource res;
- public Thread1(Resource res) {
- this.res = res;
- }
- int i=0;
- char []c = {‘A’, ‘B’, ‘C’, ‘D’, ‘E’};
- public void run() {
- synchronized (res) {
- while(i<5) {
- while(res.flag!=1) {
- try {
- res.wait();//t1
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c[i]+” “);
- i++;
- res.notifyAll();
- res.flag=2;
- }
- }
- }
- }
- class Thread2 extends Thread {
- Resource res;
- public Thread2(Resource res) {
- this.res = res;
- }
- int i=0;
- char []c = {‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘};
- public void run() {
- synchronized (res) {
- while(i<5) {
- while(res.flag!=2) {
- try {
- res.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c[i]+” “);
- i++;
- res.notifyAll();
- res.flag=3;
- }
- }
- }
- }
- class Thread3 extends Thread {
- Resource res;
- public Thread3(Resource res) {
- this.res = res;
- }
- char []c = {‘甲’,’乙’,’丙’,’丁’,’戊’};
- public void run() {
- synchronized (res) {
- for(int i=0;i<c.length;i++){
- while(res.flag!=3) {
- try {
- res.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c[i]+” “);
- res.notifyAll();
- res.flag=1;
- }
- }
- }
- }
- public class Test1 {
- public static void main(String[] args) {
- Resource res = new Resource();
- Thread1 t1 = new Thread1(res);
- Thread2 t2 = new Thread2(res);
- Thread3 t3 = new Thread3(res);
- t1.start();
- t2.start();
- t3.start();
- }
- }
明显,方法一的代码更美观,通用。