请用“等待唤醒”机制编写一个程序
要求:
第一个线程:遍历1–1000所有的数字,在遍历过程中,如果发现这个数字能同时被2,3,5,7整除,立即wait()等待,让第二个线程进入。
第二个线程:运行后,将一个计数器 + 1,之后再唤醒等待的线程。
主线程中:休息2秒,让两个线程全部执行完毕,打印“计数器”的结果。
我的代码:
> public class WaitNotifyDemo {
> static int cnt = 0;//用于次数统计
>
> public static void main(String[] args) {
> //设置锁对象
> Object object = new Object();
> //设置标记
> boolean[] flag = {false};
>
> /*第一个线程:遍历1--1000所有的数字,在遍历过程中,
> 如果发现这个数字能同时被2,3,5,7整除,立即wait()等待,让第二个线程进入。*/
> new Thread(new Runnable() {
> @Override
> public void run() {
> synchronized (object) {
> for (int i = 1; i <= 1000; i++) {
> try {
> if (i % 2 == 0 && i % 3 == 0 && i % 5 == 0 && i % 7 == 0) {
> System.out.println(Thread.currentThread().getName() + "获取数据:" + i);
> //满足条件,进入等待状态,唤醒第二个线程,进行计数。
> object.notify();
> flag[0] = true;//设置标记
> object.wait();//自己等待,让另一个行程计数
> }
> } catch (InterruptedException e) {
> e.printStackTrace();
> }
> }
> }
> }
> }).start();
>
> //第二个线程:运行后,将计数器 + 1之后再唤醒线程一。
> new Thread(new Runnable() {
> @Override
> public void run() {
> while (true) {
> synchronized (object) {
> try {
> if (flag[0]) { //如果标记变为true,让计数器+1
> System.out.println(Thread.currentThread().getName() + "计数器数值:" +
> (++cnt));
> flag[0] = false;//设置标记
> object.notify();//唤醒线程一
> object.wait();//自己等待
> }
> } catch (InterruptedException e) {
> e.printStackTrace();
> }
>
> }
> }
> }
> }).start();
>
> //main线程等待
> try {
> Thread.sleep(1000);
> } catch (InterruptedException e) {
> e.printStackTrace();
> }
> System.out.println("计数器最终数:" + cnt);
> } }