题目
借助线程同步机制对四个线程进行输出
1 线程输出:甲、乙、丙、丁、戊
2 线程输出:aa、bb、cc、dd、ee
3 线程数出:A、B、C、D、E
4 线程输出:1、2、3、4、5
最终输出效果应该为:甲 aa A 1 乙 bb B 2 丙 cc C 3 丁 dd D 4 戊 ee E 5
分析
很显然,需要用到线程“生产者消费者”案例,即 wait()和 notify()的使用。
这里可以参考
代码如下
- /*
- *
- * @author Nanait
- *
- */
- class Rescouce {
- boolean flag = true;
- }
- class Thread1 extends Thread{
- Rescouce res;
- public Thread1(Rescouce res) {
- this.res = res;
- }
- String []c1 = {“甲”,“乙”,“丙”,“丁”,“戊”};
- String []c2 = {“aa”,“bb”,“cc”,“dd”,“ee”};
- public void run() {
- synchronized (res) {
- for(int i=0;i<5;i++) {
- while(!res.flag){
- try {
- res.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c1[i]+” “);
- System.out.print(c2[i]+” “);
- res.flag=false;
- res.notifyAll();
- }
- }
- }
- }
- class Thread2 extends Thread{
- Rescouce res;
- public Thread2(Rescouce res) {
- this.res = res;
- }
- String []c1 = {“A”,“B”,“C”,“D”,“E”};
- String []c2 = {“1”,“2”,“3”,“4”,“5”};
- public synchronized void run() {
- synchronized (res) {
- for(int i=0;i<5;i++) {
- while(res.flag){
- try {
- res.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- System.out.print(c1[i]+” “);
- System.out.print(c2[i]+” “);
- res.flag=true;
- res.notifyAll();
- }
- }
- }
- }
- public class Test {
- public static void main(String[] args) {
- Rescouce res = new Rescouce();
- new Thread1(res).start();
- new Thread2(res).start();
- }
- }
运行结果