Calling child thread method from parent thread - java

I have a Chat program (running on android) that runs a ui (Chat_client) and then creates an ChatThread that runs communication. I have managed making the client thread call a parent method (using post) but not vsv. I want the parent to call the send method on the client side after the user pushes send button. Help greatly appreciated!
//BUTTON SEND METHOD in parent class. (Chat-thread is running already)
public void send (View view) {
//THIS IS NOT WORKING
chatThread.sendLine(userInput.getText().toString());
}
//Method in child class
public void sendLine (String line){
to_server.println(line);
}

Ok so after some research I arrived at the following solution.
The child thread opens the socket and then creates another thread that reads from socket. The child thread has handler and looper (message que) to which the UI thread sends messages to send through the socket.
Voila!

Related

Two threads concuration in main programm

I have program (MAIN) that has two thread that communicates with com port (COM) and TCP session (TCP).
If main (MAIN) program need info from TCP and COM modules it sends request message R (tR and cR). When threads have answer they send back answer A (tA and cA). I have problem, when I send reguest to COM (cR) and without getting answer from it have answer from TCP- tA. COM R-A should be somehow isolated from TCP interruption. How to solve this problem using JAVA 1.4 ?
UPD. On tA event MAIN initiates cR - request to COM port. Main can initiate request to COM by itself. I would like avoid to have second question to COM port without getting answer from first one.
UPD2. Actually whole system looks like picture below. cR might be started by tA or by uR. And cA can answer to TCP via tR or to UI via uA.
Following scenarios are correct
uR->cR->cA->tR-tA->cR->cA->uA
cA->tR->tA->cR
uR->cR->cA->uA
I'm getting troubles when two requests goes to COM at the same time.
cA->tR->tA->cR
uR->cR
I would like to allow new request only in case when COM returns answer to first caller.
As I understand correctly you have 2 threads in main method. 1 thread is interacting with with TCP and another with COM. Right?
If this is the case than what you can do is you can let handle thread 1 to handle all TCP request/response and thread 2 to handle all COM request/response. And the main thread is not aware of this. Until the time both thread finish their job independently the main threads wait and once both thread are done with their job, Main thread can resume its work. hence the communication of COM and TCP is completley separate. you can use Threads "join()" method here.
Did I answer your question?
You don't have to use multiple threads. Just read the request from the socket, synchronously process the request by communicating over the COM port, and then write the response over the socket.
There may be reasons to use multiple threads, though. For example, perhaps you want to be able to respond to socket requests with a time-out error if the COM port doesn't respond fast enough, but the serial port library you are using doesn't support a time-out configuration. In that case, you'll have to clarify your requirements. What do you want to happen if another request is received from the socket, but the COM thread is still stuck handling a previous request? You could wait, respond with an error immediately, etc.
Create a single-thread ExecutorService. Whenever you need to interact with the COM port, whether the request originates from the socket or from the main program itself, submit the task to this service. This will ensure that serial communications won't be interleaved with competing requests.
The basic idea here is to allow only one thread to use the COM port, consuming a queue of tasks produced by various other threads.
Here is one example that can explain your system. Here i have made a environment of caller receiver. Until caller not end with his or her statement receiver can not start with saying anything or respond to caller.
Caller.java
public class Caller implements Runnable {
MaintainACall call;
Caller(MaintainACall me)
{
call=me;
new Thread(this,"Mr X").start();
}
public void run()
{
String a[]={"Hello how r u", "I'm in vadodara"};
for(int i=0;i<2;i++)
{
call.sayHello(a[i]);
}
}
}
Receiver.java
public class Reciver implements Runnable {
MaintainACall call;
Reciver(MaintainACall call)
{
this.call=call;
new Thread(this,"Mr Y").start();
}
public void run()
{
call.Wtshesay();
}
}
MaintainACall.java
public class MaintainACall {
String say;
boolean valueSet=false;
synchronized String Wtshesay()
{
while(!valueSet)
try
{
wait();
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
System.out.println("I have heared "+say);
valueSet=false;
notify();
return say;
}
synchronized void sayHello(String msg)
{
while(valueSet)
try
{
wait();
}
catch(InterruptedException ie)
{
System.out.println(ie);
}
say=msg;
valueSet=true;
System.out.println("She says "+say);
notify();
}
}
MainClass.java
public class MainClass {
public static void main(String arg[])
{
MaintainACall my=new MaintainACall();
new Caller(my);
new Reciver(my);
}
}

Firebase listener is blocked in Java(Android)

I have a simple onChildAdded listener set, but it doesn't seem to be working:
listRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot,
String previousChildName) {
Log.d("DEBUG","A child has been added!");
// Do stuff...
}
// Other unimplemented methods for ChildEventListener here...
});
while(true);
I'm adding children to listRef but nothing happens.
The while(true) line is here on purpose to demonstrate my problem, which is that the handler is only able to fire after everything else finishes! And in this case, it never does. When I remove this line it works.
I assume that this is by design. Is there any way to make it work in these situations regardless of what comes after?
Thanks
while(true) would permanently block the thread from receiving events, since the Android client uses the main thread to post events.
It is possible to set a different thread to receive events via Config.setEventTarget()
In this case, the EventTarget is passed instances of Runnable which it is responsible for running to receive events.

Update UI from a background worker

I want to port my client from Java Swing(Java client) to Android(Android client).
Basically, my Java client have a thread, which run a forever while loop to receive UDP packets, and base on content of UDP packets, UI of the corresponding JFrame will be updated.
Now I want my Android client has a background worker like the thread in the Java client, and that worker will be initialized in the main activity. Then when there are some requests from the UDP socket, the main activity will start some corresponding activities (Chat Activities), then there are some other requests come from the UDP socket, the worker will update on the activity(this activity can be main activity or a Chat Activity) which is being displayed on the screen.
So my question is what the background worker should be:
Service
Normal Java thread
Asynctask
or what...
Which is the most appropriate with my requirements?
Thanks!
The background worker should be a service, because
A Service is an application component that can perform long-running
operations in the background and does not provide a user interface.
while your UI will be a activity, your service will read the UDP packets and the activity will be modified accordingly.
A Service is the most suitable candidate in your case.
There is a class Application class for each android application . First extend it and it will be initialized on very first time your app will start even before your Activity . Initialize/ start your normal java thread to perfrom background work here . The key advantage will be you can get instance of this application class anywhere from the app (It means you can control on the background thread from anywhere in the applicaion . Send background http request etc.. whatever ....) .Then initialize the handler on the UI thread of particular activity upon which you want to do changes and do something like this.
private Handler myHandler ;
public void checkBackgroundAndUpdateUi()
{
if(conetxt.getApplicationContext().getStatus == completed)
{
initializeHandler();
handler.postRunnable(myRunnable);
}
}
Runnable myRunnable = new Runnable(){
public void run()
{
// update your UI views here .....
}
};
private void initializeHandler(){
myHandler = new Handler ();
}

How can I implement threads in this scenario?

I haven't got any code at the moment but I have a situation where I will be implementing an Java application onto a wireless sensor. There can only be one main method.
There will be multiple other wireless sensors that can connect to my sensor. My sensor needs to do a calculation based on thhe information provided to me by the other sensors. Each sensor can choose whether or not they want to participate in the calculation. Every 1 second, my sensor does a calculation.
So basically, what I need is to listen for incoming sensors, provide them with a thread to interact with, and retrieve the information from each sensor.
My question is, in my application, how do I listen for incoming sensors (blocking call) and also free my application to carry out its calculations?
From a high level, this is what your application will do
==Main Thread==
start socket
Start processing thread
accept an incoming connection (this will cause the thread to block until a connection occurs)
start new thread to handle socket (handler thread) (alternatively use a thread pool, but that is more complicated)
return to 3
==Handler Thread==
Receive open socket from main thread
Save data coming in from socket to be given to processing thread
Finish and close socket
==Processing Thread==
Wait 1 second
Process data retrieved from step 2 of Handler Thread
Return to 1
You need another thread that receives the information of all the communication threads. You should look at the utilities in java.util.concurrent such a BlockingQueue that let threads pass data to one another thread-safely.
Most of all you should read a lot about multi-threading: it is not a trivial topic.
This will get you started. Add error/exception checking/handling as necessary.
public class Test {
static class WorkTask42 implements Runnable {
public void run() {
// background work
}
}
public static void main(String... args) throws Exception {
// repeat for each background task
WorkTask42 wt = new WorkTask42();
Thread a = new Thread(wt);
a.setDeamon(true);
a.start();
}
}

Using SwingWorker to implement a UDP Client/Server

Trying to write a UDP client-server application using Swing. Each instance of the client should be able to send messages to the Server (from the event dispatch thread) and also continuously listen for messages from other clients relayed through the server (on a worker thread using SwingWorker). I'm trying to implement a ListenWorker class now whose doInBackground method will continuously listen for UDP datagrams, and publish the data to the process() method, with will update a JTextArea on the client JFrame with the message. However, I'm running into some difficulties due to my inexperience with SwingWorker and general Swing concurrency. Here is the gist of the code I wrote so far:
public class ListenWorker extends SwingWorker<void, String> {
public ListenWorker(int port, JTextArea textArea){
// set up socket
}
protected void doInBackground(){
while(true){
// code to receive Datagram
publish(messageFromDatagram);
}
}
protected void process(List<String> messages){
for(String message : messages){
textArea.append(message);
}
}
}
However, my IDE is giving me an error in the first line where I start the class defintion, saying "illegal start of type" due to void being there. As far as I can see, I want my doInBackground to be a void method, since I intend it to run indefinitely, listening for datagrams from the various clients. Java doesn't seem to want to let me have it as a void method though. How would I code a way around this?
You probably want java.lang.Void to represent the doInBackground() return type; for example SwingWorker<Void, String>.
Addendum: doInBackground() would then return null.

Categories

Resources