使用两个线程,您应该打印“Hello World Hello World Hello World Hello World Hello World Hello World”。
在两个线程中,一个应该打印“Hello:”,另一个线程“World”。
我可以用不同的类来做到这一点,比如 hello 和 world 各一个 我也可以用内部类来做
有没有一种方法可以让只有一个主类而没有内部类?
最佳答案
Is there a way such that there's only one main class and and no inner class?
当然。您可以传入要打印到主类中的字符串。当然,棘手的部分是协调线程,以便它们实际打印出 "HelloWorld"
而不是 "WorldHello"
或其他排列。线程将在不保证顺序的情况下并行运行。这就是线程程序的全部要点——它们异步运行。试图强制输出特定的单词会否定使用线程的目的。
但是,由于每个人都对我之前的回答投了反对票,可能是因为它没有完美解决他们的家庭作业问题,我将添加一些逻辑来协调两个线程并输出“Hello World...”。
这两个线程需要能够锁定某些东西,互相发信号,并且知道它们什么时候应该等待或打印。所以我将添加一个 boolean printHello
并将锁定传入的公共(public)锁对象:
public class HelloWorld implements Runnable {
private static boolean printHello = true;
private final String toPrint;
private final boolean iPrintHello;
private final Object lock;
public static void main(String[] args) {
final Object lock = new Object();
// first thread prints Hello
new Thread(new HelloWorld("Hello ", true, lock)).start();
// second one prints World
new Thread(new HelloWorld("World ", false, lock)).start();
}
public HelloWorld(String toPrint, boolean iPrintHello, Object lock) {
this.toPrint = toPrint;
this.iPrintHello = iPrintHello;
this.lock = lock;
}
@Override
public void run() {
// don't let it run forever
for (int i = 0; i < 1000 && !Thread.currentThread().isInterrupted(); ) {
// they need to synchronize on a common, constant object
synchronized (lock) {
// am I printing or waiting?
if (printHello == iPrintHello) {
System.out.print(toPrint);
// switch the print-hello to the other value
printHello = !printHello;
// notify the other class that it can run now
lock.notify();
i++;
} else {
try {
// wait until we get notified that we can print
lock.wait();
} catch (InterruptedException e) {
// if thread is interrupted, _immediately_ re-interrupt it
Thread.currentThread().interrupt();
return;
}
}
}
}
}
}
关于java - 多线程 Hello World,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981435/