简体   繁体   English

java线程如何实现并发

[英]java thread how to achieve concurrency

I created a main class called X and two Y and Z classes.我创建了一个名为 X 的主类和两个 Y 和 Z 类。 Y and Z implements Runnable classes. Y 和 Z 实现 Runnable 类。 class X contains a static array A that can be accessed in Y and Z. The run() method of the class Y reads an input file and populates the vector A. The run() method of the Z class uses data stored into the vector A to process some data. X 类包含一个可以在 Y 和 Z 中访问的静态数组 A。Y 类的run()方法读取输入文件并填充向量 A。Z 类的run()方法使用存储在向量中的数据A 处理一些数据。

The objective of using threads in this problem is: as the vector A is filled in the run() method of class Y, the run() method of the class Z will processing the received values ​​in the vector A.在这个问题使用线程的目的是:为向量A被填充在run() Y级的方法,所述run()的类Z方法将在矢量A.处理所接收的值

To do this I did the following calls in the main method of class X:为此,我在类 X 的 main 方法中进行了以下调用:

public static void main(String[] args) {

Y objectY = new Y();           
Thread threadInput = new Thread(objectY );

threadInput.start();

Z objectZ = new Z();           
Thread threadOut = new Thread(objectZ);

threadOut.start();

Is that correct?那是对的吗? I'm getting the expected results, but don't know if the code is parallelized in fact.我得到了预期的结果,但不知道代码实际上是否并行化。 If its not parallelized, how should I do it?如果它没有并行化,我应该怎么做?

Yes, your code does kick off two separate threads that operate in parallel with the main thread.是的,您的代码确实启动了两个与主线程并行运行的独立线程。 I can't verify the correctness of the static array handling without seeing that code, but I can confirm that this is indeed parallelized.我无法在没有看到该代码的情况下验证静态数组处理的正确性,但我可以确认这确实是并行化的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM