修改一个Java程序

qq_32051499 2015-10-16 08:41:35
import java.util.concurrent.Phaser;
public class StarPhaserDemo {
public static void main(String args[]) {
Phaser phsr = new NewlinePhaser(4,3);
new StarThread(phsr);
new StarThread(phsr);
new StarThread(phsr);
new StarThread(phsr);
}
}
class NewlinePhaser extends Phaser {
int numPhases;
public NewlinePhaser(int numParties, int phases) {
super(numParties);
numPhases = phases;
}
public boolean onAdvance(int phase, int numParties) {
System.out.println(); // print a newline
return phase == numPhases-1; // stop after numPhases
}
}
class StarThread implements Runnable {
Phaser phsr;
StarThread(Phaser p) {
phsr = p;
new Thread(this).start();
}
public void run() {
while (!phsr.isTerminated()) {
System.out.print('*');
phsr.arriveAndAwaitAdvance();
}
}
}
运行程序后会看到下列输出:
****
****
****
现要求修改此程序:

1.要求不绘制矩形,而显示如下的星星三角形。
****
***
**
*
2.像原来程序一样使用4个线程,每个线程在每个阶段最多负责绘制一个星星。
...全文
71 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
oh_Maxy 版主 2015-10-16
  • 打赏
  • 举报
回复

public class StarPhaserDemo {
    public static void main(String args[]) throws InterruptedException {
        Phaser phsr1 = new NewlinePhaser(1, 4);
        new StarThread(phsr1);
        Thread.sleep(10);
        Phaser phsr2 = new NewlinePhaser(1, 3);
        new StarThread(phsr2);
        Thread.sleep(10);
        Phaser phsr3 = new NewlinePhaser(1, 2);
        new StarThread(phsr3);
        Thread.sleep(10);
        Phaser phsr4 = new NewlinePhaser(1, 1);
        new StarThread(phsr4);
        Thread.sleep(10);
    }
}

class NewlinePhaser extends Phaser {
    int numPhases;

    public NewlinePhaser(int numParties, int phases) {
        super(numParties);
        numPhases = phases;
    }

    public boolean onAdvance(int phase, int numParties) {
        boolean flag = phase == numPhases - 1;
        if(flag)
        System.out.println(); // print a newline
        return phase == numPhases - 1; // stop after numPhases
    }
}
确保线程先后顺序,还是依赖Sleep了。。

50,129

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧