[JAVA] I realized that Runnable wasn't just an interface for running in a separate thread

Introduction

In the test client application, it became necessary to send not only the contents of the definition file in order but also multiple files at the same time. When I put the Runnable implementation classes for processing in separate threads in a list and implemented them so that they are executed in another thread, I noticed that if I execute them in order, they will be executed sequentially.

table of contents

1.First of all 2. Table of contents 3. Now 4. Conclusion

While now

I've only used Runnable as the starting point for processing to be executed in another thread, but I've noticed that if I just call therun ()method, processing will be done in the same thread. ..

Runner.java


	public void start() {
		List<Runnable> runnables = new ArrayList<>();
		for (String line : getLines()) {
			runnables.add(createRunnable(line));
		}
		
		log.debug("Same thread sequential execution");
		runnables.forEach(r -> r.run());

		log.debug("Simultaneous execution of multiple threads");
		runnables.forEach(r -> new Thread(r).start());
	}

	private String[] getLines() {
		return new String[] {
			"Hello",
			"Hi",
			"How are you",
			"Bye"
		};
	}

	private Runnable createRunnable(String line) {
		//The processing to be executed differs depending on the contents of line
		if (line.length() < 5) {
			return () -> process(line, "***");
		}
		else {
			return () -> process(line);
		}
	}

	private void process(String line) {
		log.debug(Thread.currentThread().getId() + ": "+ line);
	}

	private void process(String line, String deco) {
		process(deco + line + deco);
	}

in conclusion

Recently, I've finally come into contact with Java 8 and am studying. I've been developing with Java 6 for the convenience of the projects I've been involved in. We have to change the way we think about class design.

Recommended Posts

I realized that Runnable wasn't just an interface for running in a separate thread
A story that I realized that I had to study as an engineer in the first place
I tried using an extended for statement in Java