Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Provide different range for each thread

$
0
0
I am trying to make each thread works in a particular range. So for the below example-

Number of Threads is 2
Number of Tasks is 10

Then first thread should work on 1 - 10 and second thread should work on 11 - 20.

In my current code, the only problem is for the first thread it is printing out 1 - 10 but for the second thread nextId becomes 11 and noOfTasks is still 10. So my for loop in run method doesn't works for that.

Is there any way to fix the problem?

class ThreadTask implements Runnable {
	private final int id;
	private int noOfTasks;

	public ThreadTask(int nextId, int noOfTasks) {
		this.id = nextId;
		this.noOfTasks = noOfTasks;
	}

	@Override
	public void run() {

		for (int i = id; i <= noOfTasks; i++) {
			System.out.println(i);
		}
	}
}

public class XMPTest {

	public static void main(String[] args) {

		final int noOfThreads = 2;
		final int noOfTasks = 10;

		//create thread pool with given size 
		ExecutorService service = Executors.newFixedThreadPool(noOfThreads);

		try {
			// queue some tasks 
			for (int i = 0, nextId = 1; i < noOfThreads; i++, nextId += noOfTasks) {
				service.submit(new ThreadTask(nextId, noOfTasks));
			}
			//wait for termination         
			service.shutdown();
			service.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
		} catch (Exception e) {
			
		} finally {
			System.out.println("Hello");
		}
	}
}

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>