Soyez le premier à donner votre avis sur cette source.
Snippet vu 2 560 fois - Téléchargée 1 fois
public interface Synchronizer { default Object getSynchronizer() { return this; } @FunctionalInterface interface WithResult<R> { R sync() throws RuntimeException; } default <R> R synchronize(WithResult<R> fun) throws RuntimeException { synchronized (getSynchronizer()) { return fun.sync(); } } @FunctionalInterface interface WithoutResult { void sync() throws RuntimeException; } default void synchronize(WithoutResult fun) throws RuntimeException { synchronized (getSynchronizer()) { fun.sync(); } } }
public interface Example { public void withoutResult(int n); public String withResult(int n); }
public class SynchronizedExample implements Synchronizer, Example { private final Example example; public SynchronizedExample(Example example) { this.example = example; } @Override public void withoutResult(int n) { synchronize(() -> example.withoutResult(n)); } @Override public String withResult(int n) { return synchronize(() -> example.withResult(n)); } }
@Override public Object getSynchronizer() { return example; }
public class BasicExample implements Example { private void sleep(String label) { try { System.out.println("Begin " + label); Thread.sleep(1_000); } catch (InterruptedException e) { System.err.println(e); } finally { System.out.println("Finish " + label); } } @Override public void withoutResult(int n) { sleep("withoutResult : " + n); } @Override public String withResult(int n) { sleep("withResult : " + n); return null; } }
public class Test1 { public static void main(String[] args) { Example example = new BasicExample(); new Thread(() -> example.withoutResult(1)).start(); new Thread(() -> example.withResult(2)).start(); new Thread(() -> example.withoutResult(3)).start(); new Thread(() -> example.withResult(4)).start(); } }
Begin withoutResult : 1 Begin withResult : 2 Begin withResult : 4 Begin withoutResult : 3 Finish withoutResult : 1 Finish withResult : 2 Finish withResult : 4 Finish withoutResult : 3
public class Test2 { public static void main(String[] args) { Example example = new SynchronizedExample(new BasicExample()); new Thread(() -> example.withoutResult(1)).start(); new Thread(() -> example.withResult(2)).start(); new Thread(() -> example.withoutResult(3)).start(); new Thread(() -> example.withResult(4)).start(); } }
Begin withResult : 2 Finish withResult : 2 Begin withResult : 4 Finish withResult : 4 Begin withoutResult : 1 Finish withoutResult : 1 Begin withoutResult : 3 Finish withoutResult : 3
Commentaire
Vous n'êtes pas encore membre ?
inscrivez-vous, c'est gratuit et ça prend moins d'une minute !
Les membres obtiennent plus de réponses que les utilisateurs anonymes.
Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.
Le fait d'être membre vous permet d'avoir des options supplémentaires.