I need to send some data from the main thread to another thread. I\'ve already read a lot of materials on threads, asynctasks and handlers but maybe they created some confusion
You could solve it using standard Java ways for consumer / producer problems, i.e. a BlockingQueue
consumed by a thread and any amount of threads that produce data.
public class SendingWorker {
private final BlockingQueue sendQueue = new LinkedBlockingQueue();
private volatile Socket socket;
public void start() {
thread.start();
}
public void stop() {
// interrupt so waiting in queue is interrupted
thread.interrupt();
// also close socket if created since that can block indefinitely
Socket socket = this.socket;
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// adding to queues is thread safe
public void send(Draw draw) {
sendQueue.add(draw);
}
private final Runnable task = new Runnable() {
@Override
public void run() {
try {
socket = new Socket(InetAddress.getLocalHost(), 8000);
OutputStream out = socket.getOutputStream();
while (true) {
Draw draw = sendQueue.take();
out.write(draw);
out.flush();
}
} catch (Exception e) {
// handle
} finally {
// cleanup
}
}
};
private final Thread thread = new Thread(task);
}