Last active
August 29, 2015 14:10
-
-
Save ok3141/c5bd4f1c59cc1d13defd to your computer and use it in GitHub Desktop.
How to synchronize usage of stream providing direct reference on it? One of possible solutions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.PrintStream; | |
public class Sample { | |
public static final int COUNT = 10000; | |
public static void main(String[] args) { | |
final StreamHolder holder = new StreamHolder(System.out); | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
threadOne(holder); | |
} | |
}).start(); | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
threadTwo(holder); | |
} | |
}).start(); | |
} | |
private static void threadOne(StreamHolder holder) { | |
final SampleWorkerOne worker = new SampleWorkerOne(); | |
for (int i = 0, n = COUNT; i < n; ++i) { | |
worker.head = "(my head " + i + ")"; | |
worker.body = "(my body " + i + ")"; | |
holder.doWithStream(worker); | |
sleep(20); | |
} | |
} | |
private static void threadTwo(StreamHolder holder) { | |
final SampleWorkerTwo worker = new SampleWorkerTwo(); | |
for (int i = 0, n = COUNT; i < n; ++i) { | |
worker.buffer = "(my buffer " + i + ")"; | |
holder.doWithStream(worker); | |
sleep(30); | |
} | |
} | |
private static void sleep(long millis) { | |
try { | |
Thread.sleep(millis); | |
} catch (Throwable ex) { | |
// ignore | |
} | |
} | |
} | |
interface StreamWorker { | |
void work(PrintStream out); | |
} | |
class StreamHolder { | |
private PrintStream mOut; | |
public StreamHolder(PrintStream out) { | |
mOut = out; | |
} | |
public synchronized void doWithStream(StreamWorker worker) { | |
worker.work(mOut); | |
} | |
} | |
class SampleWorkerOne implements StreamWorker { | |
String head; | |
String body; | |
@Override | |
public void work(PrintStream out) { | |
out.print("Head: "); | |
out.print(head); | |
out.print(" Body: "); | |
out.print(body); | |
out.print(" : "); | |
for (int i = 0, n = 20; i < n; ++i) { | |
out.print(i); | |
out.print('.'); | |
} | |
out.println(); | |
} | |
} | |
class SampleWorkerTwo implements StreamWorker { | |
String buffer; | |
@Override | |
public void work(PrintStream out) { | |
out.print("Buffer: "); | |
out.print(buffer); | |
out.print(" : "); | |
for (int i = 0, n = 20; i < n; ++i) { | |
out.print(i); | |
out.print('.'); | |
} | |
out.println(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is example output without
synchronized
keyword: