Java - how to write multithreaded programs?

Share a Daniel's AI tutorial. Zero basis! Easy to understand! Funny and humorous! I hope you can join the team of artificial intelligence! Pleas...

Share a Daniel's AI tutorial. Zero basis! Easy to understand! Funny and humorous! I hope you can join the team of artificial intelligence! Please click http://www.captainbed.net

Before Java 5, there were two ways to implement multithreading: one is to inherit the Thread class; the other is to implement the Runnable interface. In both ways, we need to rewrite the run() method to define the behavior of threads. The latter is recommended because inheritance in Java is single inheritance. A class has a parent class. If it inherits the Thread class, it can no longer inherit other classes. Obviously, it is more flexible to use the Runnable interface.

Add: there is a third way to create a thread after Java 5: to implement the Callable interface. The call method in the interface can generate a return value at the end of thread execution. The code is as follows:

package chimomo.learning.java.code.multithreading.callable; import java.util.concurrent.Callable; /** * @author Created by Chimomo */ class MyTask implements Callable<Integer> { private int upperBounds; public MyTask(int upperBounds) { this.upperBounds = upperBounds; } @Override public Integer call() { int sum = 0; for (int i = 1; i <= upperBounds; i++) { sum += i; } return sum; } }
package chimomo.learning.java.code.multithreading.callable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * @author Created by Chimomo */ public class MyTaskTest { public static void main(String[] args) throws Exception { List<Future<Integer>> list = new ArrayList<>(); ExecutorService service = Executors.newFixedThreadPool(10); for (int i = 0; i < 10; i++) { list.add(service.submit(new MyTask((int) (Math.random() * 100)))); } int sum = 0; for (Future<Integer> future : list) { // while(!future.isDone()) ; sum += future.get(); } System.out.println(sum); } }

3 December 2019, 09:03 | Views: 8204

Add new comment

For adding a comment, please log in
or create account

0 comments