Java - ¿Ayuda con la sincronizacion de hilos?

 
Vista:
sin imagen de perfil
Val: 98
Ha aumentado su posición en 4 puestos en Java (en relación al último mes)
Gráfica de Java

¿Ayuda con la sincronizacion de hilos?

Publicado por Francisco Emmanuel (60 intervenciones) el 12/05/2020 21:26:47
Buen día soy nuevo en esto de los hilos y me esta costando trabajo entenderlos estoy realizando un programa donde escribo un nombre con 3 hilos distintos para que los muestre de la siguiente manera 10 veces

1.- Alan Raul

2.- Alan Raul

3.- Alan Raul

....

El hilo1 se encarga de escribir el numero , el hilo2 escribe el nombre de Alan y el hilo 3 escribe el nombre de Raul el problema es que debo crear 2 hilos de hilo2 y 4 hilos de hilo3 y pues que estén sincronizados para los que los hilos de hilo2 escriban Alan y que los 4 hilos de hilo3 escriban Raul pero sin duplicar datos tengo código pero no esta funcionado correctamente me muestra los resultados de manera incorrecta:

1.- Raul Raul Raul Raul Alan Alan Raul Raul Raul

2.- Raul Alan Alan Raul Raul

estoy usando synchronized aunque no se si exista otra alternativa dejo el código que tengo al momento:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class Tipo1 extends Thread {
 
    @Override
    public void run(){
        for(int i=1 ;i <=10; i++){
            System.out.print(i+".- ");
            try{
            Tipo1.sleep(1000);
            }catch(InterruptedException e){
                System.out.println("Error en la clase tipo1"+e);
            }
        }
    }
}
 
public class Tipo2 extends Thread {
    public synchronized void EscribirNombre() {
 
        for (int i = 1; i <= 10; i++) {
            try {
                Tipo2.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Error en la clase tipo2" + e);
            }
            System.out.print("Alan ");
        }
    }
 
    @Override
    public void run() {
        EscribirNombre();
    }
}
public class Tipo3 extends Thread {
 
    public synchronized void EscSegundoNombre() {
        for (int i = 1; i <= 10; i++) {
            System.out.print("Raul ");
            try {
                Tipo3.sleep(1000);
            } catch (InterruptedException e) {
                System.out.println("Error en la clase tipo4" + e);
            }
        }
    }
 
    @Override
    public void run() {
        EscSegundoNombre();
    }
}
public class Prueba {
    public static void main(String[] args) {
 
        Tipo1 tipo1 = new Tipo1();
        Tipo2 tipo2 = new Tipo2();
        Tipo2 btipo2 = new Tipo2();
        Tipo3 tipo3 = new Tipo3();
        Tipo3 btipo3 = new Tipo3();
        Tipo3 ctipo3 = new Tipo3();
        Tipo3 dtipo3 = new Tipo3();
 
        tipo1.start();
        tipo2.start();
        btipo2.start();
        tipo3.start();
        btipo3.start();
        ctipo3.start();
        dtipo3.start();
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

¿Ayuda con la sincronizacion de hilos?

Publicado por Costero (148 intervenciones) el 13/05/2020 05:48:41
El problema esta es que los hilos corren concurrent independientemente el uno del otro. Es por que tu synchronization aqui no hace nada.
Cada vez que corres to codigo el resultado es diferente.

Una forma de tener alguna forma de orden (valga la redundancia) es utilizando los metodos wait() and notify() o notifyAll() en un mismo monitor.
Asi que un Hilo quiere correr chequea una condicion y decide o no esperar a que lo notifiquen. Lo notifican despierta esta vez la condicion is true asi que corre y hace su processo. Pone una nueva condicion que le sirva a otro hilo y notifca a todo los hilos que estan esperando.
Y asi el processo se repite.

Abajo el nuevo codigo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
public class NameWriter {
    private static final String TIPO1 = "Tipo1";
    private static final String TIPO2 = "Tipo2";
    private static final String TIPO3 = "Tipo3";
 
    private String tipo = TIPO1;
 
    public synchronized void writeTipo1(String value, int i) {
 
        while (!this.getTipo().equals(TIPO1)) {
            try {
                wait();
            } catch (InterruptedException e) {
                // don't care
            }
        }
        System.out.print("\n" + i + ".- ");
        setTipo(TIPO2);
        notifyAll();
    }
 
    public synchronized void writeTipo2(String value) {
 
        while (!this.getTipo().equals(TIPO2)) {
            try {
                wait();
            } catch (InterruptedException e) {
                // don't care
            }
        }
        System.out.print(value);
        setTipo(TIPO3);
        notifyAll();
    }
 
    public synchronized void writeTipo3(String value) {
 
        while (!this.getTipo().equals(TIPO3)) {
            try {
                wait();
            } catch (InterruptedException e) {
                // don't care
            }
        }
        System.out.print(value);
        setTipo(TIPO1);
        notifyAll();
    }
 
    private void setTipo(String tipo) {
        this.tipo = tipo;
    }
 
    private String getTipo() {
//        System.out.println("Tipo is: " + tipo);
        return this.tipo;
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Tipo1 extends Thread {
 
    private final NameWriter nameWriter;
 
    public Tipo1(NameWriter nameWriter) {
        this.nameWriter = nameWriter;
    }
 
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            this.nameWriter.writeTipo1("\ni+.- ", i);
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Tipo2 extends Thread {
 
    private final NameWriter nameWriter;
 
    public Tipo2(NameWriter nameWriter) {
        this.nameWriter = nameWriter;
    }
 
    @Override
    public synchronized void run() {
        for (int i = 1; i <= 10; i++) {
            this.nameWriter.writeTipo2("Alan ");
        }
    }
 
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Tipo3 extends Thread {
 
    private final NameWriter nameWriter;
 
    public Tipo3(NameWriter nameWriter) {
        this.nameWriter = nameWriter;
    }
 
    @Override
    public synchronized void run() {
        for (int i = 1; i <= 10; i++) {
            this.nameWriter.writeTipo3("Raul ");
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Prueba {
    public static void main(String[] args) {
 
       NameWriter nameWrite = new NameWriter();
 
        Tipo1 tipo1 = new Tipo1(nameWrite);
        Tipo2 tipo2 = new Tipo2(nameWrite);
        Tipo2 btipo2 = new Tipo2(nameWrite);
        Tipo3 tipo3 = new Tipo3(nameWrite);
        Tipo3 btipo3 = new Tipo3(nameWrite);
        Tipo3 ctipo3 = new Tipo3(nameWrite);
        Tipo3 dtipo3 = new Tipo3(nameWrite);
 
        tipo1.start();
        tipo2.start();
        tipo3.start();
//        btipo2.start();
//        btipo3.start();
//        ctipo3.start();
//        dtipo3.start();
 
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 98
Ha aumentado su posición en 4 puestos en Java (en relación al último mes)
Gráfica de Java

¿Ayuda con la sincronizacion de hilos?

Publicado por Francisco Emmanuel (60 intervenciones) el 13/05/2020 06:24:32
Tu respuesta me parece buena solo que debo iniciar tambien los hilos
1
2
3
4
btipo2.start();
btipo3.start();
ctipo3.start();
dtipo3.start();

osea el tipo2 y btipo2 deben trabajar ambos si no pues tiene caso de que instancie el btipo2 y no lo inicie ya que ese hilo en realidad como tu lo pones no esta haciendo nada y mi problema es que si lo inicio btipo2.start() el programa no termina de ejecutarse que peudo hacer
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

¿Ayuda con la sincronizacion de hilos?

Publicado por Costero (148 intervenciones) el 13/05/2020 19:39:35
La razon por la que not termina el program es por que los Hilos no han muerto.

Por ejemplo: Si tienes 2 hilos of Tipo3. Una escribe 4 nombres y el otro escribe 6 nombres. El for loop no ha terminado en ellos y por eso el hilo no termina.

Una tecnica seria decirle a los hilos, 'ya no haces falta' osea un Kill switch. Codigo abajo:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
public class NameWriter {
    private static final String TIPO1 = "Tipo1";
    private static final String TIPO2 = "Tipo2";
    private static final String TIPO3 = "Tipo3";
    private static final String KILL = "KILL";
 
    private String tipo = TIPO1;
    private boolean isLast = false;
 
    public synchronized void writeTipo1(String value, int i) {
 
        while (!this.getTipo().equals(TIPO1)) {
            try {
                wait();
            } catch (InterruptedException e) {
                // don't care
            }
        }
        System.out.print(value);
        setTipo(TIPO2);
        notifyAll();
    }
 
    public synchronized void writeTipo2(String value) {
 
        while (!this.getTipo().equals(TIPO2) && !this.isKill()) {
            try {
                wait();
            } catch (InterruptedException e) {
                // don't care
            }
        }
 
        if(!this.isKill()) {
            System.out.print(value);
            setTipo(TIPO3);
        }
        notifyAll();
    }
 
    public synchronized void writeTipo3(String value) {
 
        while (!this.getTipo().equals(TIPO3) && !this.isKill()) {
            try {
                wait();
            } catch (InterruptedException e) {
                // don't care
            }
        }
 
        if(!this.isKill()) {
            System.out.print(value);
        }
 
        if(isLast()) {
            setTipo(KILL);
        } else {
            setTipo(TIPO1);
        }
        notifyAll();
    }
 
    public void setTipo(String tipo) {
        this.tipo = tipo;
    }
 
    private String getTipo() {
        return this.tipo;
    }
 
    public synchronized boolean isKill() {
        return getTipo().equals(KILL);
    }
 
    private boolean isLast() {
        return isLast;
    }
 
    public synchronized boolean setLast(boolean isLast) {
        return this.isLast = isLast;
    }
 
}
 
 
 
 
public class Tipo1 extends Thread {
 
    private final NameWriter nameWriter;
 
    public Tipo1(NameWriter nameWriter) {
        this.nameWriter = nameWriter;
    }
 
    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            this.nameWriter.writeTipo1("\n" + i + ".- ", i);
            if(i == 10) {
                this.nameWriter.setLast(true);
            }
        }
    }
}
 
 
 
public class Tipo2 extends Thread {
 
    private final NameWriter nameWriter;
 
    public Tipo2(NameWriter nameWriter) {
        this.nameWriter = nameWriter;
    }
 
    @Override
    public void run() {
        for (int i = 1; i <= 10 && !this.nameWriter.isKill(); i++) {
            this.nameWriter.writeTipo2("Alan ");
        }
    }
 
}
 
 
 
public class Tipo3 extends Thread {
 
    private final NameWriter nameWriter;
 
    public Tipo3(NameWriter nameWriter) {
        this.nameWriter = nameWriter;
    }
 
    @Override
    public void run() {
        for (int i = 1; i <= 10 && !this.nameWriter.isKill(); i++) {
            this.nameWriter.writeTipo3("Raul ");
        }
    }
}
 
 
 
public class Prueba {
    public static void main(String[] args) {
 
       NameWriter nameWrite = new NameWriter();
 
        Tipo1 tipo1 = new Tipo1(nameWrite);
        Tipo2 tipo2 = new Tipo2(nameWrite);
        Tipo2 btipo2 = new Tipo2(nameWrite);
        Tipo3 tipo3 = new Tipo3(nameWrite);
        Tipo3 btipo3 = new Tipo3(nameWrite);
        Tipo3 ctipo3 = new Tipo3(nameWrite);
        Tipo3 dtipo3 = new Tipo3(nameWrite);
 
        tipo1.start();
        tipo2.start();
        tipo3.start();
        btipo2.start();
        btipo3.start();
        ctipo3.start();
        dtipo3.start();
 
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil
Val: 14
Ha aumentado su posición en 8 puestos en Java (en relación al último mes)
Gráfica de Java

¿Ayuda con la sincronizacion de hilos?

Publicado por Francisco (10 intervenciones) el 21/05/2020 18:25:19
Muchas gracias costero en verdad me ayudaste como no tienes idea me funciono a la perfección y una disculpa por la tardanza al contestar solo que estas semanas he estado al full con tareas y trabjos
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

¿Ayuda con la sincronizacion de hilos?

Publicado por Tom (1831 intervenciones) el 21/05/2020 21:42:29
¿ No funcionaría algo como esto ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class DummyThreads extends Thread {
	static final Object monitor = new Object();
	static volatile Integer curOrder = 0;
	static volatile Integer curLine = 0;
	final Integer order;
	final String text;
	final boolean last;
 
	/* */
	public DummyThreads(Integer order, String text, boolean isLast) {
		this.order = order;
		this.text = text;
		this.last = isLast;
	}
	/* */
	public void run() {
		while(curLine < 10) {
			synchronized(monitor) {
				try {
					monitor.wait();
				} catch(InterruptedException ex) {
					Logger.getLogger(DummyThreads.class.getName()).log(Level.SEVERE, null, ex);
				}
				monitor.notifyAll();
				if(curOrder.equals(order)) {
					System.out.print(text);
					if(this.last) {
						System.out.println();
						curLine++;
						if(curLine == 10) {
							break;
						}
						curOrder = 0;
					} else {
						curOrder++;
					}
					System.out.flush();
				}
			}
		}
	}
	/* */
	public static void main(String args[]) throws InterruptedException {
		DummyThreads[] thrs = new DummyThreads[3];
 
		thrs[0] = new DummyThreads(0, "Col.1 ", false);
		thrs[1] = new DummyThreads(1, "Col.2 ", false);
		thrs[2] = new DummyThreads(2, "Col.3", true);
 
		for(Thread t : thrs) {
			t.start();
		}
		synchronized(monitor) {
			monitor.notifyAll();
		}
		for(Thread t : thrs) {
			t.join();
		}
		System.out.flush();
	}
}

run:
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
Col.1 Col.2 Col.3
BUILD SUCCESSFUL (total time: 0 seconds)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

¿Ayuda con la sincronizacion de hilos?

Publicado por Tom (1831 intervenciones) el 22/05/2020 00:53:10
Aunque, para ese esquema de esperar por una condición ... parece más apropiado usar algo así:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class DummyThreads extends Thread {
	static final Lock lock = new ReentrantLock();
	static final Condition wakeUp = lock.newCondition();
	static volatile Integer curOrder = 0;
	static volatile Integer curLine = 0;
	final Integer order;
	final String text;
	final boolean last;
 
	/* */
	public DummyThreads(Integer order, String text, boolean isLast) {
		this.order = order;
		this.text = text;
		this.last = isLast;
	}
	/* */
	public void run() {
		while(true) {
			lock.lock();
			try {
				while(!order.equals(curOrder)) {
					try {
						wakeUp.await();
					} catch(InterruptedException ex) {
						Logger.getLogger(DummyThreads.class.getName()).log(Level.SEVERE, null, ex);
					}
				}
				wakeUp.signalAll();
				System.out.print(text);
				if(last) {
					System.out.println();
					curLine++;
					curOrder = 0;
					if(curLine >= 10) {
						break;
					}
				} else {
					curOrder++;
					if(curLine >= 9) {
						break;
					}
				}
			} finally {
				lock.unlock();
			}
		}
	}
	/* */
	public static void main(String args[]) throws InterruptedException {
		DummyThreads[] thrs = new DummyThreads[3];
 
		thrs[0] = new DummyThreads(0, "Col.1 ", false);
		thrs[1] = new DummyThreads(1, "Col.2 ", false);
		thrs[2] = new DummyThreads(2, "Col.3", true);
 
		for(Thread t : thrs) {
			t.start();
		}
		for(Thread t : thrs) {
			t.join();
		}
	}
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar