Java – Java and Spring Examples http://localhost/wordpress Wed, 26 Jun 2019 15:04:13 +0000 fr-FR hourly 1 https://wordpress.org/?v=5.0.4 Thread using « ExecutorService, Executors, Callable » and « ForkJoinPool, RecursiveTask » http://localhost/wordpress/2017/04/20/thread-executorservice-executors-callable-forkjoinpool-recursivetask/ Thu, 20 Apr 2017 12:11:59 +0000 http://codercocoon.com/?p=311
This example presents how to handle a pool of threads using : ExecutorService, Executors, Callable and ForkJoinPool, RecursiveTask.

Get the sources of the example from the following GitHub url : https://github.com/javaspringexamples/ThreadHandlePool.git

Or Download a .zip file : https://github.com/javaspringexamples/ThreadHandlePool/archive/master.zip

package javaspringexamples.ThreadExamples;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.IntStream;

/**
 * This example represents how to create a pool of threads using ExecutorService
 * and Callable interfaces.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class ListInitializerCallable implements Callable<List<Integer>> {

	int[] data;

	public ListInitializerCallable(int[] data) {
		this.data = data;
	}

	/**
	 * Method call() to override for Callable objects.
	 */
	@Override
	public List<Integer> call() throws Exception {
		ArrayList<Integer> l = new ArrayList<>();
		for (int i = 0; i < data.length; i++) {
			l.add(data[i] % 2);
		}
		return l;
	}

	/**
	 * The main method.
	 * 
	 * @param args
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public static void main(String[] args) throws InterruptedException, ExecutionException {

		int lenght = 10000;

		ListInitializerCallable li1 = new ListInitializerCallable(IntStream.range(0, lenght / 2).toArray());
		ListInitializerCallable li2 = new ListInitializerCallable(IntStream.range((lenght / 2), lenght).toArray());

		// Fixing the pool to 2 threads
		ExecutorService es = Executors.newFixedThreadPool(2);
		Future<List<Integer>> f1 = es.submit(li1);
		Future<List<Integer>> f2 = es.submit(li2);

		// Getting the list returned of the 1st thread.
		List<Integer> l1 = f1.get();
		// Getting the list returned of the 2nd thread.
		List<Integer> l2 = f2.get();
		// Merging the two lists.
		l1.addAll(l2);

		System.out.println(l1.size());
		System.out.println(l1);

		// Shutting down the ExecutorService
		es.shutdown();
	}

}
package javaspringexamples.ThreadExamples;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

/**
 * This example represents how to create a pool of threads using ForkJoinPool
 * and extending the RecursiveTask class.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class ListInitializerRecursiveTask extends RecursiveTask<List<Integer>> {

	private int[] data;
	private int begin;
	private int end;

	public ListInitializerRecursiveTask(int[] data, int _begin, int _end) {
		this.data = data;
		begin = _begin;
		end = _end;
	}

	/**
	 * Method compute() to override for RecursiveTask objects, we initiate the
	 * list recursively.
	 */
	@Override
	protected List<Integer> compute() {
		List<Integer> l = new ArrayList<>();

		int middle = (end - begin) / 2;
		if (middle > 500) {
			ListInitializerRecursiveTask li1 = new ListInitializerRecursiveTask(data, begin, (begin + middle));
			li1.fork();
			ListInitializerRecursiveTask li2 = new ListInitializerRecursiveTask(data, (begin + middle), end);
			l = li2.compute();
			l.addAll(li1.join());
		} else {
			for (int i = begin; i < end; i++) {
				l.add(data[i] % 2);
			}
		}
		return l;
	}

	/**
	 * The main method.
	 * 
	 * @param args
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	public static void main(String[] args) throws InterruptedException, ExecutionException {

		int lenght = 10000;
		ListInitializerRecursiveTask li1 = new ListInitializerRecursiveTask(IntStream.range(0, lenght).toArray(), 0,
				lenght);

		// Initiating the ForkJoinPool
		ForkJoinPool fjp = new ForkJoinPool();
		// Getting the list initiated recursively
		List<Integer> l = fjp.invoke(li1);

		System.out.println(l.size());
		System.out.println(l);
	}
}
]]>
Thread : How to use wait() and notify() methods to handle synchronisation between threads http://localhost/wordpress/2017/04/19/thread-methods-wait-notify/ Wed, 19 Apr 2017 08:21:17 +0000 http://codercocoon.com/?p=301
This example shows how to use notify() and wait() methods of Thread class.

Get the sources of the example from the following GitHub url : https://github.com/javaspringexamples/ThreadNotifyWait.git

Or Download a .zip file : https://github.com/javaspringexamples/ThreadNotifyWait/archive/master.zip

Thread-1 is waiting...
Thread-0: Says the field soccer is no more available.P1 please gets in my player and have fun.
Thread-3 is waiting...
P1 shoots ball 1
Thread-2 is waiting...
P1 shoots ball 2
P1 shoots ball 3
P1 shoots ball 4
P1 shoots ball 5
P1 shoots ball 6
P1 shoots ball 7
P1 shoots ball 8
P1 shoots ball 9
P1 shoots ball 10
Thread-0: Says the field soccer is available.
Dear threads get notified...!
Thread-1 is notified...
Thread-1: Says the field soccer is no more available.P2 please gets in my player and have fun.
P2 shoots ball 1
P2 shoots ball 2
P2 shoots ball 3
P2 shoots ball 4
P2 shoots ball 5
P2 shoots ball 6
P2 shoots ball 7
P2 shoots ball 8
P2 shoots ball 9
P2 shoots ball 10
Thread-1: Says the field soccer is available.
Dear threads get notified...!
Thread-3 is notified...
Thread-3: Says the field soccer is no more available.P4 please gets in my player and have fun.
P4 shoots ball 1
P4 shoots ball 2
P4 shoots ball 3
P4 shoots ball 4
P4 shoots ball 5
P4 shoots ball 6
P4 shoots ball 7
P4 shoots ball 8
P4 shoots ball 9
P4 shoots ball 10
Thread-3: Says the field soccer is available.
Dear threads get notified...!
Thread-2 is notified...
Thread-2: Says the field soccer is no more available.P3 please gets in my player and have fun.
P3 shoots ball 1
P3 shoots ball 2
P3 shoots ball 3
P3 shoots ball 4
P3 shoots ball 5
P3 shoots ball 6
P3 shoots ball 7
P3 shoots ball 8
P3 shoots ball 9
P3 shoots ball 10
Thread-2: Says the field soccer is available.
Dear threads get notified...!
All balls shooted.
package javaspringexamples.ThreadExamples;

/**
 * This example shows how to use notify() and wait() methods of Thread class.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class Player extends Thread {

	private String name;
	private SoccerField sf;

	public Player(String _name, SoccerField _sf) {
		name = _name;
		sf = _sf;
	}

	/**
	 * If the soccer field is available, then the player gets in to shoot balls.
	 */
	public void shootBalls() {
		sf.setAvailable(false);
		System.out.println(getName() + ": Says the field soccer is no more available." + name
				+ " please gets in my player and have fun.");
		for (int i = 1; i <= 10; i++)
			System.out.println(name + " shoots ball " + i);
		System.out.println(getName() + ": Says the field soccer is available.");
		sf.setAvailable(true);
	}

	@Override
	public void run() {
		sf.getSoccerField();
		shootBalls();
	}

	/**
	 * The main method.
	 */
	public static void main(String[] args) throws InterruptedException {
		SoccerField sf = new SoccerField();
		Player p1 = new Player("P1", sf);
		Player p2 = new Player("P2", sf);
		Player p3 = new Player("P3", sf);
		Player p4 = new Player("P4", sf);
		p1.start();
		p2.start();
		p3.start();
		p4.start();
		// Waiting for threads terminating their jobs.
		p1.join();
		p2.join();
		p3.join();
		p4.join();
		System.out.println("All balls shooted.");
	}
}
package javaspringexamples.ThreadExamples;

/**
 * This example shows how to use notify() and wait() methods of Thread class.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class SoccerField {
	private boolean available = true;

	/**
	 * If the soccer field is not available, then the thread will wait until
	 * being notified that the soccer field is available again.
	 */
	public synchronized void getSoccerField() {
		if (!available) {
			try {
				System.out.println(Thread.currentThread().getName() + " is waiting...");
				wait();
				System.out.println(Thread.currentThread().getName() + " is notified...");
			} catch (InterruptedException e) {
				// Do something to handle the InterruptedException
				e.printStackTrace();
			}
		}
	}

	/**
	 * When the soccer field is available, the other threads are notified to
	 * continue doing their jobs.
	 * 
	 */
	public synchronized void setAvailable(boolean a) {
		available = a;
		if (a) {
			notify();
			System.out.println("Dear threads get notified...!");
		}
	}

	public boolean isAvailable() {
		return available;
	}
}
]]>
Thread methods : getId, getName, isAlive, sleep, interrupt http://localhost/wordpress/2017/04/18/thread-getid-getname-isalive-sleep-interrupt/ Tue, 18 Apr 2017 08:07:59 +0000 http://codercocoon.com/?p=297
This example presents some popular methods about Thread, especially: getId, getName, isAlive, sleep, interrupt.

Get the sources of the example from the following GitHub url : https://github.com/javaspringexamples/ThreadPopularMethods.git

Or Download a .zip file : https://github.com/javaspringexamples/ThreadPopularMethods/archive/master.zip

package javaspringexamples.ThreadExamples;

/**
 * This class presents how to implement a thread by extending the Thread class,
 * and using sleep method.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class ThreadByExtension extends Thread {

	public ThreadByExtension(String name) {
		super(name);
	}

	@Override
	public void run() {
		System.out.println("Running " + getName());
		try {
			// Using sleep method.
			sleep(1000);
		} catch (InterruptedException e) {
			// ...Do something to handle the exception.
			System.out.println(getName() + " is interrupted");
		}
	}
}
package javaspringexamples.ThreadExamples;

/**
 * This class presents how to implement a thread by implementing the Runnable
 * interface, and using sleep method.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class ThreadByImplementation implements Runnable {

	@Override
	public void run() {
		try {
			System.out.println("Running " + this.getClass().getName());
			Thread.sleep(6000);
		} catch (InterruptedException e) {
			// ...Do something to handle the exception.
			System.out.println(Thread.currentThread().getName() + " is interrupted");
		}

	}
}
package javaspringexamples.ThreadExamples;

/**
 * This class presents some popular methods about threads, especially : getId,
 * getName, isAlive, sleep, interrupt.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class TestThread {

	public static void main(String[] args) throws InterruptedException {

		// Thread by extending the Thread class.
		ThreadByExtension t1 = new ThreadByExtension("t1");
		t1.start();
		System.out.println("t1 isAlive=" + t1.isAlive());

		// Thread by implementing the Runnable interface.
		Thread t2 = new Thread(new ThreadByImplementation(), "t2");
		t2.start();
		// Interrupting t2
		t2.interrupt();

		// Thread by implementing the Runnable interface anonymously.
		Runnable r1 = new Runnable() {
			@Override
			public void run() {
				System.out.println("Running Anonymous object runnable.");
			}
		};
		Thread t3 = new Thread(r1);
		t3.start();

		// Thread by implementing the Runnable interface anonymously using
		// lambda expression.
		Runnable r2 = () -> System.out.println("Running runnable object using lambda expression Runnable.");
		Thread t4 = new Thread(r2);
		t4.start();

		// Waiting for the t1 to be terminated.
		t1.join();

		// t1.is Alive will be always false, because t1 is terminated.
		System.out.println(t1.getId() + " " + t1.getName() + " " + t1.getPriority() + " isAlive=" + t1.isAlive());
		System.out.println(t2.getId() + " " + t2.getName() + " " + t2.getPriority());
		// The threads names are generated by the JVM, they begin by "Thread-"
		System.out.println(t3.getId() + " " + t3.getName() + " " + t3.getPriority());
		System.out.println(t4.getId() + " " + t4.getName() + " " + t4.getPriority());

	}
}
]]>
Thread : creation threads by extending Thread class, and implementing Runnable interface http://localhost/wordpress/2017/04/17/thread-creation-extending-thread-implementing-runnable-interface/ Mon, 17 Apr 2017 12:56:06 +0000 http://codercocoon.com/?p=291
This class presents the different ways to implement threads : extending the Thread class, implementing the Runnable interface anonymously and using lambda expression.

Get the sources of the example from the following GitHub url : https://github.com/javaspringexamples/ThreadCreationExamples.git.

Or Download a .zip file : https://github.com/javaspringexamples/ThreadCreationExamples/archive/master.zip.

package javaspringexamples.ThreadExamples;

/**
 * This class presents how to implement a thread by extending the Thread class.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class ThreadByExtension extends Thread {

	@Override
	public void run() {
		System.out.println("Running " + this.getClass());
	}
}
package javaspringexamples.ThreadExamples;

/**
 * This class presents how to implement a thread by implementing the Runnable
 * interface.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class ThreadByImplementation implements Runnable {

	@Override
	public void run() {
		System.out.println("Running " + this.getClass().getName());
	}
}
package javaspringexamples.ThreadExamples;

/**
 * This class presents the different ways to implement threads.
 * 
 * @author mounir.sahrani@gmail.com
 *
 */
public class TestThread {

	public static void main(String[] args) {

		// Thread by extending the Thread class.
		ThreadByExtension t1 = new ThreadByExtension();
		t1.start();

		// Thread by implementing the Runnable interface.
		Thread t2 = new Thread(new ThreadByImplementation());
		t2.start();

		// Thread by implementing the Runnable interface anonymously.
		Runnable r1 = new Runnable() {
			@Override
			public void run() {
				System.out.println("Running Anonymous object runnable.");
			}
		};
		Thread t3 = new Thread(r1);
		t3.start();

		// Thread by implementing the Runnable interface anonymously using
		// lambda expression.
		Runnable r2 = () -> System.out.println("Running runnable object using lambda expression Runnable.");
		Thread t4 = new Thread(r2);
		t4.start();
	}
}
]]>