Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package hilos;
- import java.awt.FlowLayout;
- import javax.swing.JFrame;
- import static javax.swing.JFrame.EXIT_ON_CLOSE;
- import javax.swing.JPanel;
- import javax.swing.JTextField;
- public class Hilos extends JFrame{
- private JTextField jf,jd;
- public Hilos(){
- setLayout(new FlowLayout(FlowLayout.CENTER));
- jf=new JTextField(50);
- jd=new JTextField(50);
- add(jf);
- add(jd);
- CCorriente cc=new CCorriente();
- RunnableThreadGiro rtg=new RunnableThreadGiro(cc);
- RunnableThreadDeposito rtd=new RunnableThreadDeposito(cc);
- Thread t1=new Thread(rtg);
- Thread t2=new Thread(rtd);
- t1.start();
- t2.start();
- setVisible(true);
- setDefaultCloseOperation(EXIT_ON_CLOSE);
- setSize(600,600);
- try{
- t1.join();
- t2.join();
- }catch(InterruptedException ex){
- }
- }
- public class RunnableThreadDeposito extends JPanel implements Runnable{
- private final CCorriente cc;
- public RunnableThreadDeposito(CCorriente cc){
- this.cc=cc;
- }
- @Override
- public void run(){
- while(true){
- try{
- Thread.sleep((long) (1 + (int) (Math.random() * 5000)));
- cc.deposito((int) (Math.random() * 10000));
- }catch(InterruptedException ex){
- }
- }
- }
- }
- public class RunnableThreadGiro extends JPanel implements Runnable{
- private final CCorriente cc;
- public RunnableThreadGiro(CCorriente cc){
- this.cc=cc;
- }
- @Override
- public void run(){
- while(true){
- try{
- Thread.sleep((long) (1+ (int) (Math.random() * 5000)));
- cc.giro((int) (Math.random() * 10000));
- }catch(InterruptedException ex){
- }
- }
- }
- }
- public class CCorriente{
- private final int MAX_SALDO=100000;
- private int saldo=0;
- public synchronized void deposito(int dinero){
- try{
- while(saldo>=MAX_SALDO){
- wait();
- }
- saldo+=dinero;
- jf.setText(" Deposito: " +dinero + " Saldo: " +getSaldo());
- setVisible(true);
- notifyAll();
- }catch(InterruptedException ex){
- }
- }
- public synchronized void giro(int dinero){
- try{
- while(saldo<=0){
- wait();
- }
- saldo-=dinero;
- jd.setText(" Giro: " +dinero + " Saldo: " +getSaldo());
- setVisible(true);
- notifyAll();
- }catch(InterruptedException ex){
- }
- }
- private int getSaldo(){
- return saldo;
- }
- }
- public static void main(String[] args) {
- Hilos h=new Hilos();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment