英文:
java threads and multithreading:How to synchronize threads
问题
import java.util.Scanner;
class ThreadSum extends Thread {
public void run() {
int n, sum = 0, num;
Scanner sc = new Scanner(System.in);
System.out.println("请输入值的数量:");
n = sc.nextInt();
System.out.println("请输入数字:");
for (int i = 0; i < n; i++) {
num = sc.nextInt();
sum = sum + num;
}
System.out.println("总和为:" + sum);
}
}
class ThreadPro extends Thread {
public void run() {
int n, pro = 1, num;
Scanner sc = new Scanner(System.in);
System.out.println("请输入值的数量:");
n = sc.nextInt();
System.out.println("请输入数字:");
for (int i = 0; i < n; i++) {
num = sc.nextInt();
pro = pro * num;
}
System.out.println("乘积为:" + pro);
}
}
class Pro {
public static void main(String args[]) {
ThreadSum ts = new ThreadSum();
ts.start();
try {
ts.join(); // 等待第一个线程执行完毕
} catch (InterruptedException e) {
e.printStackTrace();
}
ThreadPro tp = new ThreadPro();
tp.start();
}
}
英文:
I was doing my college assignment for java which includes a program for find sum and product of n numbers using two threads.I have written the following code however the threads are overlapping one another ie-code of both threads are being executed simultaneously.Someone please help me to rewrite the code so that the after only one thread finishes execution,the other one may start.Thanks in advance
import java.util.Scanner;
class ThreadSum extends Thread {
public void run() {
int n, sum = 0, num;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no of values");
n = sc.nextInt();
System.out.println("Enter numbers");
for (int i = 0; i < n; i++) {
num = sc.nextInt();
sum = sum + num;
}
System.out.println("The sum is:" + sum);
}
}
class ThreadPro extends Thread {
public void run() {
int n, pro = 1, num;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no of values");
n = sc.nextInt();
System.out.println("Enter numbers");
for (int i = 0; i < n; i++) {
num = sc.nextInt();
pro = pro * num;
}
System.out.println("The product is:" + pro);
}
}
class pro {
public static void main(String args[]) {
ThreadSum ts = new ThreadSum();
ts.start();
ThreadPro tp = new ThreadPro();
tp.start();
}
}
答案1
得分: -1
请查看我在https://stackoverflow.com/a/65677134/14346734中的答案。
请记住:线程是异步的。如果您需要它们同步,请不要使用线程。
请编辑并告诉我们您的观点。
英文:
Take a look at my answer in https://stackoverflow.com/a/65677134/14346734.
Remember: threads are asynchronous. If you need them to be synchronous, don't use threads.
Please edit and let us know your point.
专注分享java语言的经验与见解,让所有开发者获益!
评论