java无忧网

标题: 线程类采用实现Runnable接口的方式。诗歌存为String 数组。所有线程都是从该数组中 [打印本页]

作者: java无忧网    时间: 2020-4-13 15:34
标题: 线程类采用实现Runnable接口的方式。诗歌存为String 数组。所有线程都是从该数组中
4.9 日多线程课程作业
编程
模拟集体诗朗诵的场景(四人同时朗诵一首诗,每人一句。)
编程要求
“床前明月光,疑是地上霜,举头望明月,低头思故乡”
编写一个包含四个线程的程序,要求诗歌中的诗句由不同的线程依次输出。
Tips:线程类采用实现Runnable接口的方式。诗歌存为String 数组。所有线程都是从该数组中获取要输出的内容。
注意:编程题要求形成word文档提交。代码和运行截图 word文档的构成内容。
注意本周日将进行第二次单元测。测试内容为线程之前的内容(包括线程内容)
代码:
public class TestMain {
        public static ReadString read;
        public static void main(String[] args) {
                Object lock = new Object();
                read = new ReadString();
                new ReadThread(0, read, lock).start();
                new ReadThread(1, read, lock).start();
                new ReadThread(2, read, lock).start();
                new ReadThread(3, read, lock).start();
        }
}
class ReadString {
        private String[] read = { "床前明月光","疑是地上霜","举头望明月","低头思故乡" };
        public synchronized void read(int id, int index) {
                if (index >3)
                        return;
                System.out.print("Thread :" + id + " read String :" + read[index] + " \n");
        }
}
class ReadThread extends Thread {
        private int threadId;
        private ReadString reads;
        private Object lock;
        private final int COUNT = 4;
        public static volatile int flag = 0;
        public ReadThread(int id, ReadString read, Object lock) {
                this.threadId = id;
                this.reads = read;
                this.lock = lock;
        }
        @Override
        public void run() {
                // TODO Auto-generated method stub
                while (true) {
                        synchronized (lock) {
                                if ((flag % COUNT) == threadId) {
                                        reads.read(threadId, flag);
                                        flag++;
                                        lock.notifyAll();
                                } else {
                                        try {
                                                lock.wait();
                                        } catch (InterruptedException e) {
                                                // TODO Auto-generated catch block
                                                e.printStackTrace();
                                        }
                                }
                        }
                }
        }
}








欢迎光临 java无忧网 (http://www.javawyw.com/) Powered by Discuz! X3.2