java 用java线程编写一个程序,打印如下序列2 3 4 6 6 9 8 12 10(序列中2和3的倍数)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11709536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Write a program using java threads to print the following sequence 2 3 4 6 6 9 8 12 10 (Multiple of 2 and 3 in a sequence)
提问by philip
Basically what it does is that it prints the following numbers multiple of 2 and 3 in sequence like this
基本上它的作用是像这样按顺序打印以下 2 和 3 的倍数
2 3 4 6 6 9 8 12 10 = this is the output
(2*1=2) (3*1=3) (2*2=4) (3*2=6) (2*3=6) (3*3=9) (2*4=8) (3*4=12) (2*5=10) = just a guide
here's my code so far, I'm having trouble displaying it in sequence. I've tried using wait and notify but it's a mess. So far this one is working.
到目前为止,这是我的代码,我无法按顺序显示它。我试过使用等待和通知,但它是一团糟。到目前为止,这个正在工作。
public class Main {
public static void main(String[] args) throws InterruptedException {
final Thread mulof2 = new Thread(){
public void run() {
for (int i = 1; i <= 10; i++) {
int n = 2;
int result = n * i;
System.out.print(result + " ");
}
}
};
Thread mulof3 = new Thread(){
public void run() {
for (int i = 1; i <= 10; i++) {
int n = 3;
int result = n * i;
System.out.print(result + " ");
}
}
};
mulof2.start();
mulof3.start();
}
}
采纳答案by Marko Topolnik
With Java 7 your first choice should be a Phaser
. You'll only need one instance of it, created with new Phaser(1)
. You'll need just two methods for coordination: arrive
and awaitAdvance
.
对于 Java 7,您的首选应该是Phaser
. 你只需要它的一个实例,用new Phaser(1)
. 您只需要两种协调方法:arrive
和awaitAdvance
。
回答by Monica
Multiplication Table in java using Threads Concept
java中使用线程概念的乘法表
public class Multiplication extends Thread {
public void run() {
for (int i = 1; i < 10; i++) {
int n = 2;
int result = n * i;
System.out.print(i+"*"+n+"="+result+"\n");
}
}
public static void main(String[] args) throws InterruptedException {
Multiplication mul=new Multiplication();
mul.start();
}
}
回答by Munish
Below is the code that will give you desired results.
下面的代码将为您提供所需的结果。
public class Main {
公共课主要{
public static void main(String[] args) throws InterruptedException {
final Object lock1 = new Object();
final Object lock2 = new Object();
final Thread mulof2 = new Thread(){
public void run() {
for (int i = 1; i <= 10; i++) {
synchronized (lock1) {
synchronized (lock2) {
lock2.notify();
int n = 2;
int result = n * i;
printResult(result);
}
try {
lock1.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
Thread mulof3 = new Thread(){
public void run() {
for (int i = 1; i <= 10; i++) {
synchronized (lock2) {
synchronized (lock1) {
lock1.notify();
int n = 3;
int result = n * i;
printResult(result);
}
try {
lock2.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
};
mulof2.start();
mulof3.start();
}
static void printResult(int result)
{
try {
// Sleep a random length of time from 1-2s
System.out.print(result + " ");
Thread.sleep(new Random().nextInt(1000) + 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
回答by Vitaliy
Instead of printing duringcomputation, you can aggregate the results into strings and then print both strings in order. After joining with the threads of course.
您可以将结果聚合为字符串,然后按顺序打印两个字符串,而不是在计算期间打印。当然是在加入线程之后。
回答by JB Nizet
wait()
and notify()
are generally too low level, and too complex to use. Try using a more high-level abstraction like Semaphore
.
wait()
并且notify()
通常级别太低,使用起来太复杂。尝试使用更高级的抽象,例如Semaphore
.
You could have a pair of Semaphore instances: one which allows printing the next multiple of 2, and another one which allows printing the next multiple of 3. Once the next multiple of 2 has been printed, the thread should give a permit to print the next multiple of 3, and vice-versa.
你可以有一对 Semaphore 实例:一个允许打印下一个 2 的倍数,另一个允许打印下一个 3 的倍数。一旦打印了下一个 2 的倍数,线程应该允许打印下一个 3 的倍数,反之亦然。
Of course, the initial numbers of permits of the semaphores must be 1 for the multiple-of-2 semaphore, and 0 for the other one.
当然,2的倍数的信号量的初始许可数必须为1,其他的必须为0。
回答by afrin216
A simple modification would help you get the required sequence.
一个简单的修改将帮助您获得所需的序列。
You need to declare a semaphore as other have pointed out private Semaphore semaphore;
. Then declare another variable to denote which thread has to execute next such as private int threadToExecute;
.
您需要像其他人指出的那样声明一个信号量private Semaphore semaphore;
。然后声明另一个变量来表示接下来必须执行哪个线程,例如private int threadToExecute;
.
Next step is within your thread execute the code between semaphore.acquire();
and semaphore.release();
下一步是你的线程中执行代码之间semaphore.acquire();
和semaphore.release();
thread2:
线程2:
try{
semaphore.acquire();
if(threadToExecute ==2)
semaphore.release();
//write your multiply by 2 code here
threadToExecute = 3;
semaphore.release();
}catch(Exception e){
//exceptions
}
This will nicely synchronize your output.
这将很好地同步您的输出。