Discussion:
treads y en run tomar parametros
(demasiado antiguo para responder)
_XaToA_
2003-10-15 00:43:30 UTC
Permalink
No se si me estoy haciendo un lio, que seguro tambien.
Estoy haciendo unas clases y hasta ahora nunca me habia metido con threads.
las clases que estoy haciendo , que son tres lo que pretenden es enviar
correos que se sacan, los emails, de una base de datos y dejan el proceso
haciendose.
es decir
tengo la clase principal en la que obtengo el email, titulo del mensaje y
mensaje y llamo a la clase boletin
Boletin b = new Boletin();
b.dandoCaina(email,titulo,mensaje);

la clase boletin llama a ProcesoSegundoPlano haciendo un thread cada vez. El
codigo es:
public class Boletin{
public Boletin() {
}
public void dandoCaina(String email,String titulo,String mensaje){
Thread process;
ProcesoSegundoPlano ps = new
ProcesoSegundoPlano(email,titulo,mensaje);
process = new Thread(ps);
process.start();
}
}

la clase segundo palno sería la que enviaria emails pero en ella no puedo
acceder a las variables que le paso desde la anterior, osea no puedo acceer
a email,titulo y mensaje.
el codigo es:
public class ProcesoSegundoPlano extends Thread {

String email="",titulo="",mensaje="";
public ProcesoSegundoPlano(String email,String titulo,String mensaje) {
email = this.email;
titulo = this.titulo;
mensaje = this.mensaje;
System.out.println(email + "." + titulo + "." + mensaje);
}
public void run() {
try {
System.out.println(email + "-" + titulo + "-" + mensaje);
} catch (Exception e) {
e.printStackTrace();
}
}
}

En esta ultima clase , dentro del run() no consigo imprimir el email, titulo
y mensaje, osea lo que le paso desde la anterior clase, porlo cual no puedo
enviar emails, que es mi objetivo.

Me podríais ayudar a ver como en run podría acceder a las variables que le
paso?
mcuhas gracias a todos.
Un saludo
Jorge
2003-10-15 09:02:53 UTC
Permalink
Yo diría que el problema es este:

email = this.email;
titulo = this.titulo;
mensaje = this.mensaje;

La asignación debería ser al reves. ;-)

De todas maneras, te pongo lo que pone en la documentación del JDK:

Y cuando lo leas, parecerá que estás ejecutando mal el thread. No estoy
seguro de si esto afecta, pero prueba a hacerlo como explica.
Ya que ProcesoEnSegundoPlano extiende de Thread, ejecutalo directamente, y
no
lo pases como parametro a un objeto Thread, que espera sólo un objeto
Runnable.

Espero haberte ayudado.

-------------------------------------------------------------------
-------------------------------------------------------------------
-------------------------------------------------------------------

A thread is a thread of execution in a program. The Java Virtual Machine
allows
an application to have multiple threads of execution running concurrently.

Every thread has a priority. Threads with higher priority are executed in
preference to threads with lower priority. Each thread may or may not also
be marked as a daemon. When code running in some thread creates a new
Thread
object, the new thread has its priority initially set equal to the priority
of
the creating thread, and is a daemon thread if and only if the creating
thread
is a daemon.

When a Java Virtual Machine starts up, there is usually a single non-daemon
thread (which typically calls the method named main of some designated
class).
The Java Virtual Machine continues to execute threads until either of the
following occurs:

The exit method of class Runtime has been called and the security manager
has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning from
the call to the run method or by throwing an exception that propagates
beyond
the run method.
There are two ways to create a new thread of execution. One is to declare a
class to be a subclass of Thread. This subclass should override the run
method
of class Thread. An instance of the subclass can then be allocated and
started.
For example, a thread that computes primes larger than a stated value could
be
written as follows:



---------------------------------------------------------------------------
-----

class PrimeThread extends Thread {
long minPrime;
PrimeThread(long minPrime) {
this.minPrime = minPrime;
}

public void run() {
// compute primes larger than minPrime
. . .
}
}


---------------------------------------------------------------------------
-----

The following code would then create a thread and start it running:


PrimeThread p = new PrimeThread(143);
p.start();

The other way to create a thread is to declare a class that implements the
Runnable interface. That class then implements the run method. An instance
of
the class can then be allocated, passed as an argument when creating
Thread,
and started. The same example in this other style looks like the following:



---------------------------------------------------------------------------
-----

class PrimeRun implements Runnable {
long minPrime;
PrimeRun(long minPrime) {
this.minPrime = minPrime;
}

public void run() {
// compute primes larger than minPrime
. . .
}
}


---------------------------------------------------------------------------
-----

The following code would then create a thread and start it running:


PrimeRun p = new PrimeRun(143);
new Thread(p).start();

Every thread has a name for identification purposes. More than one thread
may
have the same name. If a name is not specified when a thread is created, a
new name is generated for it.
Joe Smith
2003-10-16 09:48:43 UTC
Permalink
Post by Jorge
Y cuando lo leas, parecerá que estás ejecutando mal el thread. No estoy
seguro de si esto afecta, pero prueba a hacerlo como explica.
Ya que ProcesoEnSegundoPlano extiende de Thread, ejecutalo directamente, y
no
lo pases como parametro a un objeto Thread, que espera sólo un objeto
Runnable.
Por cierto, cabe preguntarse también si hacer una clase derivada de Thread
es la mejor solución... He leído por ahí que la solución más aceptada es
implementar Runnable, puesto que lo que tú quieres que se ejecute en un
thread separado, y en realidad, no estás definiendo una clase que sea un
tipo especial de Thread.


Saludos.
Edusshh
2003-10-16 21:01:38 UTC
Permalink
Post by Joe Smith
Post by Jorge
Y cuando lo leas, parecerá que estás ejecutando mal el thread. No estoy
seguro de si esto afecta, pero prueba a hacerlo como explica.
Ya que ProcesoEnSegundoPlano extiende de Thread, ejecutalo directamente, y
no
lo pases como parametro a un objeto Thread, que espera sólo un objeto
Runnable.
Por cierto, cabe preguntarse también si hacer una clase derivada de Thread
es la mejor solución... He leído por ahí que la solución más aceptada es
implementar Runnable, puesto que lo que tú quieres que se ejecute en un
thread separado, y en realidad, no estás definiendo una clase que sea un
tipo especial de Thread.
Saludos.
La aceptación de implementar la interfaz Runnable por encima de extender
la clase Thread básicamente se debe a que sólo podemos extender una
clase y, sin embargo, podemos implementar todas las interfaces que
queramos. ¿Qué pasa entonces si queremos extender una clase que ya
habíamos programado o que está en algún api a la vez que queremos
extender la clase Thread?
Por la contra, ambas implementaciones son válidas y perfectamente
compatibles. Así que es una opción personal del programador...

Edusshh
Free Software 4 a FreeWorld (Support Linux)

Loading...