import java.lang.Thread.State;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * {@link <a href=
 * "https://[Log in to view URL]"
 * target= "_blank">Condivizione di una risorsa tra processi</a>}
 * 
 * @author itammb ( Italia Massimiliano Buscati )
 * @version JDK 1.15
 *
 */
class Main {

	private static class ThreadParam extends Thread {
		@Override
		public void run() {
			try {
				long[] arr = new long[1];
				arr[0] = getId();

				Shared.method(arr);

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				System.out.println("Thread -> " + getId() + " ha terminato");
			}
		}
	}

	private static class Shared {
		private static long resource; // risorsa condivisa non sincronizzata ( in lettura e scrittura )

		public static void method(long[] idBuffer) throws InterruptedException {

			resource = Long.valueOf(idBuffer[0]);
			System.out.println("ingresso -> valore risorsa condivisa = " + resource + "\r\n"
					+ "ingresso -> parametro passato        = " + idBuffer[0] + "\r\n"
					+ "ingresso -> thread corrente          = " + Thread.currentThread().getId() + "\r\n");
			Thread.sleep(10);

			System.out.println("corpo -> valore risorsa condivisa = " + resource + "\r\n"
					+ "corpo -> parametro passato        = " + idBuffer[0] + "\r\n"
					+ "corpo -> thread corrente          = " + Thread.currentThread().getId() + "\r\n");
			Thread.sleep(10);

			if (idBuffer[0] != resource) {
				System.out.println("uscita -> valore risorsa condivisa = " + resource + "\r\n"
						+ "uscita -> parametro passato        = " + idBuffer[0] + "\r\n"
						+ "uscita -> thread corrente          = " + Thread.currentThread().getId() + "\r\n");
			} else
				System.out.println("uscita -> thread corrente = " + Thread.currentThread().getId() + "\r\n"
						+ "uscita -> la JVM non ha passato il controllo a un thred diverso" + "\r\n");
		}
	}

	private static class ThreadSynch extends Thread {
		private ObjectShared objectShared;
		private String msg;

		@Override
		public void run() {
			// oggetto sincronizzato
			synchronized (objectShared) {
				objectShared.send(msg);
			}
		}

		/*
		 * @Override public void run() { objectShared.send(msg); }
		 */
		public ThreadSynch(String msg, ObjectShared objectShared) {
			this.msg = msg;
			this.objectShared = objectShared;
		}
	}

	public static class ObjectShared {
		public void send(String msg) {
			System.out.println("LETTO   -> " + msg);

			try {
				Thread.sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
			}

			System.out.println("INVIATO -> " + msg);
		}
	}

	public static class RunnableShared implements Runnable {
		private long id = 0;
		private boolean notShoutdown = true;

		public boolean isNotShoutdown() {
			return notShoutdown;
		}

		public void shoutdown() {
			this.notShoutdown = false;
		}

		public long newId() {
			return ++id;
		}

		@Override
		public void run() {
			while (isNotShoutdown())
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				};
		}
	}

	public static class N_Thread extends Thread {
		RunnableShared shared;

		@Override
		public void run() {
			synchronized (shared) {
				System.out.println("Thread -> " + getId() + " :: modifica contatore ->" + shared.newId());

				try {
					shared.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		public N_Thread(RunnableShared shared) {
			this.shared = shared;
		}
	}

	private static class UniTestMultyThreds {

		/**
		 * @see Thread#currentThread()
		 * @see Thread#join()
		 * 
		 */
		public void applayMultyThreads() throws InterruptedException {
			ThreadParam[] buffer = new ThreadParam[3];
			for (int i = 0; i < 3; i++) {
				buffer[i] = new ThreadParam();
				buffer[i].start();
			}

			for (int i = 0; i < 3; i++)
				buffer[i].join();
		}

		public void applayResourceShared() throws InterruptedException {

			ObjectShared send = new ObjectShared();

			ThreadSynch S1 = new ThreadSynch(" Hi  ", send);
			ThreadSynch S2 = new ThreadSynch(" Bye ", send);

			S1.start();
			S2.start();

			S1.join();
			S2.join();
		}

		public void applayTokenMonitor() throws InterruptedException {
			RunnableShared shared = new RunnableShared();

			Thread thread = new Thread(shared);
			thread.start();

			List<Thread> listT = new ArrayList<Thread>();
			for (int i = 0; i < 10; i++) {
				Thread tx = new N_Thread(shared);
				listT.add(tx);
				tx.start();
			}

			while (isAllState(listT.iterator(), State.TERMINATED))
				synchronized (shared) {
					shared.notifyAll();
				};
				
			shared.shoutdown();
		}

		public boolean isAllState(Iterator<Thread> iterator, State state) {
			while (iterator.hasNext()) {
				Thread thread = iterator.next();
				System.out.println("Thread -> " + thread.getId() + " :: status ->" + thread.getState());
				if (! thread.getState().equals(state))
					return true;
			}

			return false;
		}
	}

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

		// Unit test - dinamica di un multy-threds :: scoope e passaggio di parametri su
		// un metodo 'non sincronizzato'
		new UniTestMultyThreds().applayMultyThreads();

		// Unit test - accesso a una risorsa condivisa
		// new UniTestMultyThreds().applayResourceShared();

		// Unit test - acquisizione del token di esecuzione 
		// new UniTestMultyThreds().applayTokenMonitor();
	}
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: