gpt4 book ai didi

java - 打印定时线程

转载 作者:行者123 更新时间:2023-11-30 08:37:45 24 4
gpt4 key购买 nike

我正在做以下作业:

Consider a shared counter whose values are non-negative integers, initially zero. A time-printing thread increments the counter by one and prints its value each second from the start of execution. A message-printing thread prints a message every fifteen seconds. Have the message-printing thread be notified by the time-printing thread as each second passes by. Add another message-printing thread that prints a different message every seven seconds. Such addition must be done without modifying the time-printing thread implementation.

Have all involved threads share the counter object that is updated by the time-printing thread every second. The time-printing thread will notify other threads to read the counter object each time it updates the counter, then each message-printing thread will read the counter value and see if its assigned time period has elapsed; if so, it will print its message.

import java.lang.Class;
import java.lang.Object;

public class Main2 {

public static void main(String... args)
{
Thread thread = new Thread()
{
public void run()
{
int x = 0;
while(true)
{
x = x + 1;
System.out.print(x + " ");
if(x%7 == 0)
{
System.out.println();
System.out.println("7 second message");
}
if(x%15 == 0)
{
System.out.println();
System.out.println("15 second message");
}
try { Thread.sleep(1000); }
catch (Exception e) { e.printStackTrace(); }
}
}
};
thread.start();
}
}

这会输出我想要的结果,但要求在 7 秒和 15 秒消息显示时要求多线程输出。我不知道如何使用多线程来执行此操作。

最佳答案

您必须在 if 条件之后删除 ";"

  if(x%7 == 0);

 if(x%15 == 0);

检查下面的代码

public static void main(String... args) {
Thread thread = new Thread() {
public void run() {
int x = 0;
while (true) {
x = x + 1;
System.out.print(x + " ");
if (x % 7 == 0)
{
System.out.println();
System.out.println("7 second message");
}
if (x % 15 == 0)
{
System.out.println();
System.out.println("15 second message");
}
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
thread.start();
}

我的输出如下

1 2 3 4 5 6 7 
7 second message
8 9 10 11 12 13 14
7 second message
15
15 second message
16 17 18 19 20 21
7 second message
22 23 24 25 26 27 ...

关于java - 打印定时线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36972685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com