Java - Pausar y reanudar hilos (2) en una fábrica de papel

 
Vista:
sin imagen de perfil

Pausar y reanudar hilos (2) en una fábrica de papel

Publicado por enrique (6 intervenciones) el 31/10/2018 07:40:08
Estoy realizando un proyecto que necesito poner 4 botones:
Inicio, Pausa, Detener y Reanudar.
trabajo con hilos pero el detalle es que no se como pausar ni reanudar los hilos.
les paso a continuacion las 3 clases que utilizo.
El programa trata de que uno le añada la cantidad de papeles y la cantidad de cajas. Las cajas se llenan dependiendo de los papeles que uno desee pero en el transcurso hay que pausarlo y ahi el detalle.



CLASE Fabrica.java
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
 
public class Fabrica  extends JFrame implements ActionListener
{
 
        JPanel P1,P2,P4,P5;
        JScrollPane P3;
        private JLabel JLabelCPapeles,JLabelCCajas;
        private JTextField CantidadPapeles,CantidadCajas;
        private JButton Star;
     	private JButton Stop;
    	private JButton Suspender;
    	private JButton Reanudar;
    	private JTextArea impresion;
 
 
		public Fabrica()
		{
		// Debo colocarlo, no olvidar 
                    setSize(1000,1000);
                        P1 =new JPanel();
		    JLabelCPapeles=new JLabel("Cantidad de Papeles");
		    CantidadPapeles=new JTextField(10);
		    JLabelCCajas = new JLabel("Cantidad de Cajas");
		    CantidadCajas=new JTextField(10);
 
		    P1.add(JLabelCPapeles);
		    P1.add(CantidadPapeles);
		    P1.add(JLabelCCajas);
		    P1.add(CantidadCajas);
 
		    P2 = new JPanel();
		    Star = new JButton("Star");
		    Star.addActionListener(this);
		    Stop = new JButton("Stop");
		    Stop.addActionListener(this);
		    Suspender = new JButton("Suspender");
		    Suspender.addActionListener(this);
		    Reanudar = new JButton("Reanudar");
		    Reanudar.addActionListener(this);
 
		    P2.add(Star);
		    P2.add(Stop);
		    P2.add(Suspender);
		    P2.add(Reanudar);
 
		    impresion = new JTextArea(30,15);
		   P3= new JScrollPane(impresion);
 
 
 
		    P5 = new JPanel(new BorderLayout());
		    P5.add(P1,BorderLayout.NORTH);
		    P5.add(P2,BorderLayout.CENTER);
		    P5.add(P3,BorderLayout.SOUTH);
		    Star.setEnabled(true);
                    Reanudar.setEnabled(false);
                    Suspender.setEnabled(false);
                    Stop.setEnabled(false);
		    this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
		    this.add(P5);
		}
 
 
		@Override
		public void actionPerformed(ActionEvent arg0) {
 
			if(arg0.getSource()==Star)
			{
			Star.setEnabled(false);
			Reanudar.setEnabled(false);
                        Suspender.setEnabled(true);
                        Stop.setEnabled(true);
                        try{
		        String papel= CantidadPapeles.getText();
                        String cantCa =CantidadCajas.getText();
                        cantCajas = new Integer(cantCa).intValue();
			cantPapel = new Integer(papel).intValue();
                        int papeles = Integer.parseInt(papel);
                        int cajas = Integer.parseInt(cantCa);
                        if((papeles==0)||(cajas==0)||(papeles==0)&&(cajas==0)){
                           throw new Exception("Ingrese un numero");
                        }
                        }catch(NumberFormatException ex){
                            JOptionPane.showMessageDialog(null, "No es un numero");
                            Star.setEnabled(true);
                            Reanudar.setEnabled(false);
                            Suspender.setEnabled(false);
                            Stop.setEnabled(false);
                            CantidadPapeles.requestFocus();
                            CantidadPapeles.setText("");
                            CantidadCajas.setText("");
                        }catch(Exception e){
                            JOptionPane.showMessageDialog(null, e.toString());
                            Star.setEnabled(true);
                            Reanudar.setEnabled(false);
                            Suspender.setEnabled(false);
                            Stop.setEnabled(false);
                            CantidadPapeles.setText("");
                            CantidadCajas.setText("");
                            CantidadPapeles.requestFocus();
                        }
 
                                cajita = new Caja(cantCajas,cantPapel);
				g1 = new ThreadGroup("t");
				thread = new Thread[3];
				persona  = new  Persona[3];
				supervisor = new Supervisor(cajita, 4,impresion);
				consumer2 = new Thread(g1,supervisor ,"t");
		        consumer2.setDaemon(true);
				consumer2.start();
			try {
			for (int i= 0; i < 3; i++)
            {
             persona[i] = new  Persona(cajita,i+1,impresion);
		       thread[i] = new Thread (g1,persona[i],"t");
		       thread[i].start();
				thread[i].join(20);
                                if(arg0.getSource()==Suspender){ //Aqui no se que hacer
                            Star.setEnabled(false);
                            Reanudar.setEnabled(true);
                            Suspender.setEnabled(false);
                            Stop.setEnabled(false);
                            persona[i].detener();
                            thread[i].wait();
                        }
            }
			}catch(InterruptedException e){}
			}
 
 
 
 
		}
 
 
 
 
	public static void main(String [] args)
	{
		java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
 
               Fabrica fabr= new Fabrica();
 
               fabr.setVisible(true);
 
 
 
            }
        }
        );
	}
 
 
 
 
	boolean  done;
	 public Caja cajita;
	public Thread [] thread;
	public Persona persona [];
	public ThreadGroup g1;
	public Supervisor supervisor;
	public Thread consumer2;
	int cantPapel=0;
	int cantCajas=0;
   String papeles;
   String canCaja;
 
 
}


CLASE Caja.java
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
public class Caja
{
    boolean noTengo=false;
    private static int cantPapelActual=0;
    private static int cantCajaActual;
    private static int cantMaxCaja;
    private static int cantMaxPapel;
 
    public Caja(int cantMaxCaja,int cantMaxPapel )
    {
    	this.cantMaxCaja= cantMaxCaja;
    	this.cantMaxPapel= cantMaxPapel;
    }
 
    Caja() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
 
    public synchronized boolean isNoTengo()
    {
       return noTengo;
    }
 
    public synchronized void setNoTengo(boolean b)
    {
       noTengo = b;
    }
 
    public synchronized void agregarPapel()
    {
       cantPapelActual++;
    }
 
    public synchronized int getCantPapelActual()
    {
       return(cantPapelActual);
    }
 
     public synchronized void setCantPapelActual(int cant)
    {
       cantPapelActual=cant;
    }
 
     public synchronized int getCantMaxPapel()
    {
       return(cantMaxPapel);
    }
 
     public synchronized void setCantMaxPapel(int cant)
    {
       cantMaxPapel=cant;
    }
    public synchronized int getCantCajaActual()
    {
       return(cantCajaActual);
    }
 
    public synchronized void setCantCajaActual(int cant)
    {
       cantCajaActual=cant;
    }
 
     public synchronized int getMaxCantCajas()
    {
       return(cantMaxCaja);
    }
 
    public synchronized void setMaxCantCajas(int cant)
    {
       cantMaxCaja=cant;
    }
 
}


CLASE persona.java
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
import javax.swing.JTextArea;
 
 
public class Persona extends Thread
{
    //public boolean iterar;
	private Caja caja;
        public boolean iterar = false;
	private int id=0;
    private JTextArea impresion;
 
    public Persona(Caja caja, int id,JTextArea impresion)
    {
 		this.caja = caja;
 		this.id = id;
        this.impresion=impresion;
    }
 
 
 
    public void run()
   	{
  		int tiempo = 0;
  	   	while(iterar)
       	{
			synchronized(caja)
  		  	{
  		     	while(!caja.isNoTengo())
  				{
  			   		try
			   		{
 
 
	  				caja.wait(1000);
   		   	   		}catch(InterruptedException e){}
  			   		break;
  				}
       	  	}
 
	 if (caja.getCantCajaActual() != caja.getMaxCantCajas())
       {
	  	try
	  	  {
 
		tiempo = (int) (Math.random()* 100 + 1);
		Thread.sleep(1000);
	  	}catch(InterruptedException e){}
 
  if(caja.getCantPapelActual() < caja.getCantMaxPapel() && caja.getCantCajaActual() != caja.getMaxCantCajas())
	{
	  caja.setNoTengo(iterar);
	  synchronized(caja)
	   {
  			addPapel();
 
  			impresion.append("\nPersona "+ id +" Puso Papel: "+caja.getCantPapelActual());
 
			caja.notifyAll();
		}
	}
} else{	break;
      }
}
 return;
}
 
  public synchronized void addPapel()
    {
       caja.agregarPapel();
    }
 
 public void start(){
      iterar = true;
      new Thread(this).start();
}
 
public void detener(){
      iterar = false;
  }
 
  public void reiniciar(){
   id=0;
  }
}


CLASE Supervisor.java
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
import javax.swing.JTextArea;
 
 
public class Supervisor extends Thread
{
	private Caja caja;
	private int id;
        private int i=0;
        private JTextArea impresion;
 
    public Supervisor(Caja caja, int id,JTextArea impresion)
    {
        this.caja = caja;
        this.id=id;
        this.impresion=impresion;
    }
 
    public void run()
   	{
  	 int tiempo = 100;
  	 while(true)
      {
	   synchronized(caja)
  		 {
  		   while(caja.isNoTengo())
  		    {
	  if (caja.getCantCajaActual() != caja.getMaxCantCajas())
		 {
  		   try
			   {
 
	   			System.out.println("\nSupervisor: "+id+"is waiting");
	  			caja.wait(1000);
   		   	   	}catch(InterruptedException e){}	  }
  	     break;
  		    }
       } // end synchronized
	    //Consumer try to take  the box
	  try
	  {
 //System.out.println("Supervisor Verify if the box full");
		tiempo = (int) (Math.random()* 1 + 1);
		Thread.sleep(tiempo);
	  }catch(InterruptedException e){}
 
	if( caja.getCantPapelActual() == caja.getCantMaxPapel())
		{
		 caja.setNoTengo(false);
		 synchronized(caja)
		  {
		   if (caja.getCantCajaActual() != caja.getMaxCantCajas())
		  	 {
		  	  quitarCaja();
		  	 // System.out.println("\nSupervisor: "+id+" quita la cajeta: "+caja.getCantCajaActual());
		  	  impresion.append("\nSupervisor: "+ id +" quita la cajeta: "+caja.getCantCajaActual());
		  	caja.notifyAll();
			caja.setNoTengo(true);
			}else{
				  caja.notifyAll();
				  break;
				  }
			   }
 		  }
 		}
   	}
 
public synchronized void quitarCaja()
    {
       caja.setCantPapelActual(0);
       caja.setCantCajaActual(++i);
 
    }
 
 }
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