1024programmer Java javarunnable method_How to implement a method on an object that implements Runnable in Java?

javarunnable method_How to implement a method on an object that implements Runnable in Java?

I have an object called OBJ which implements Runnable.

It has some members, a constructor, a run() method and a getter for a specific count (one of the members).

In my main method, I have an array of threads, each thread is a new OBJ, and each thread does a certain calculation in the run() method and saves it in the count .

Now, I want to make another loop (in addition to the one where I have started all the threads) and have each thread wait for it to complete and then use the count getter to count all the counts I get from the threads .

How to reach the getter through thread?

Workaround:

Okay, create the OBJ instance before reaching the thread loop:

List objects = new ArrayList();

// Create your objects here

for (int i = 0; i <NUM_OF_OBJ; ++i) {

objects.add(new OBJ());

}

// Run the threads

List threads = new ArrayList();

for (int i = 0; i <NUM_OF_OBJ; ++i) {

Thread t = new Thread(objects.get(i));

threads.add(t);

t.start();

}

// Wait for the threads to finish

for (Thread t : threads) {

t.join();

}

// Sum all counts

int sum = 0;

for (OBJ object : objects) {

sum += object.getCount();

}

Tag:java,multithreading,getter

Source: https://codeday.me/bug/20190621/1250460.html

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/javarunnable-method_how-to-implement-a-method-on-an-object-that-implements-runnable-in-java/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索