Monday, November 11, 2013

Treinamento Java 2 Básico - Capítulo 6 Threads


Capítulo 6  Threads - sessão 10


  1. package visao;


  2. import modelo.Ex1MinhaThread;


  3. public class Ex1UsaThread {


  4. public static void main(String[] args) {


  5. System.out.println("****INICIO MAIN****");


  6. // 1) Para criar uma thread, deve-se instanciar um objeto da classe.
  7. // O construtor pode receber como parâmetro o nome da Thread.

  8. Ex1MinhaThread mt1 = new Ex1MinhaThread("Thread-1");
  9. Ex1MinhaThread mt2 = new Ex1MinhaThread("Thread-2");
  10. Ex1MinhaThread mt3 = new Ex1MinhaThread("Thread-3");


  11. // 2) Para colocá-la em execução, utiliza-se o método start()

  12. mt1.start();
  13. mt2.start();
  14. mt3.start();


  15. // As threads são finalizadas quando seu método run() chega ao fim

  16. System.out.println ("****FIM MAIN****");
  17. }
  18. }

Abaixo temos a classe Ex1MinhaThread.java:

  1. package modelo;

  2. // 1) herança da classe Thread

  3. // Classe Thread: pertence ao java.lang
  4. public class Ex1MinhaThread extends Thread{

  5.     public Ex1MinhaThread( String s ){
  6.         this.setName(s);
  7.     }
  8.     // 2) implementar o método run, que será executado quando start for invocado
  9.     @Override // Uma thread termina quando seu método run() chega ao fim
  10.     public void run () {
  11.         System.out.println ("Início: " + getName());
  12.         for (int i = 0; i < 10; i++)
  13.             System.out.println ( getName() + "-" + i );
  14.         System.out.println ("Fim: " + getName());
  15.     }
  16. }

  17. /* Operações sobre Threads
  18. - interrupt(): interrompe a thread;
  19.     No método run, deve-se testar se a thread está
  20.     interrompida através do método isInterrupted(), para
  21.     fazer o tratamento final dos recursos utilizados pela thread;
  22. - sleep(long): suspende a thread por um período determinado (ms);
  23.     Se a thread for interrompida enquanto estiver suspensa, a
  24.     exceção InterruptedException é lançada pelo método sleep;
  25. - join() ou join(long): espera até a thread terminar;
  26.     Uma thread pode esperar pela finalização de outra por
  27.     meio de uma chamada ao método join();
  28. - yield(): suspende a thread corrente, permitindo que
  29.     outras sejam executadas;
  30.  */
O resultado da execução do programa Ex1UsaThread será o que está abaixo mas pode variar dependendo do sistema operacional e do instante que eu executo o programa(se eu executar novamente o programa o resultado será completamente diferente):



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. package visao;

  2. import modelo.Ex4DadoA;
  3. import modelo.Ex4P1;
  4. import modelo.Ex4P2;

  5. public class Ex4UsaDadoA {

  6.     public static void main(String[] args) {
  7.         Ex4DadoA a = new Ex4DadoA( 5 ) ;

  8.         Ex4P1 ta1 = new Ex4P1( a ) ;
  9.         Ex4P2 ts2 = new Ex4P2( a ) ;

  10.         Ex4P1 ta3 = new Ex4P1( a ) ;
  11.         Ex4P2 ts4 = new Ex4P2( a ) ;

  12.         ta1.start() ;      
  13.         ts2.start() ;
  14.         ts4.start() ;
  15.         ta3.start() ;
  16.     }
  17. }


O exemplo abaixo é da classe Ex4DadoA que está sendo instanciada na linha 10 do programa acima:

  1. package modelo;

  2. public class Ex4DadoA {

  3.     private int a ;
  4.    
  5.     public Ex4DadoA( int ini ){
  6.         a = ini ;
  7.     }
  8.     
  9.     // synchronized: impede acesso ao mesmo objeto
  10.     public synchronized void add( int v ){
  11.         a = a + v ;
  12.         System.out.println( "Somou 1 => a = " + a ) ;
  13.     }

  14.     // synchronized: impede acesso ao mesmo objeto
  15.     public synchronized void sub( int v ){
  16.         a = a - v ;
  17.         System.out.println( "Subtraiu 1 => a = " + a ) ;
  18.     }
  19. }
O exemplo abaixo é da classe Ex4P1 que está sendo instanciada na linha 12 do programa Ex4UsaDadoA:

  1. package modelo;

  2. public class Ex4P1 extends Thread {
  3.     private Ex4DadoA a ;

  4.     public Ex4P1( Ex4DadoA a ){
  5.         this.a = a ;
  6.     }
  7.     public void run(){
  8.         a.add(1);
  9.     }
  10. }

O exemplo abaixo é da classe Ex4P2 que está sendo instanciada na linha 12 do programa Ex4UsaDadoA:


  1. package modelo;

  2. public class Ex4P2 extends Thread{
  3.     private Ex4DadoA a ;

  4.     public Ex4P2( Ex4DadoA a ){
  5.         this.a = a ;
  6.     }
  7.     public void run(){
  8.         a.sub(1);
  9.     }
  10. }



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. package visao;

  2. import java.util.*;

  3. public class ExemploThreads {

  4.     public static void main(String args[]) {

  5. TestThread t1, t2, t3;

  6.         t1 = new TestThread("Thread 01",(int)(Math.random() * 2000));
  7.         t2 = new TestThread("Thread 02",(int)(Math.random() * 2000));
  8.         t3 = new TestThread("Thread 03",(int)(Math.random() * 2000));

  9.         t1.setPriority(1);
  10.         t3.setPriority(10);
  11.         
  12.         t1.start();
  13.         t2.start();
  14.         t3.start();

  15.         try {
  16.             t1.join();
  17.             t2.join();
  18.             t3.join();
  19.         } catch (InterruptedException e) { }
  20.     }
  21. }

  22. class TestThread extends Thread {

  23.     private int tempoDeEspera;

  24.     public TestThread(String s, int tpEspera) {
  25.         
  26. super ( s );

  27. tempoDeEspera = tpEspera;
  28.     }

  29.     public void run() {
  30.         try {
  31.             sleep(tempoDeEspera);
  32.         } catch (InterruptedException e) { }

  33. System.out.println( getName() + " - " + new Date());
  34.     }
  35. }





xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. package visao;

  2. public class ThreadTest 
  3. {

  4.     public static void main(String[] args) 
  5.     {
  6.         PrintThread thread1, thread2, thread3, thread4;

  7.         thread1 = new PrintThread("Thread 01");
  8.         thread2 = new PrintThread("Thread 02");
  9.         thread3 = new PrintThread("Thread 03");
  10.         thread4 = new PrintThread("Thread 04");

  11.         System.out.println("\nInicializando Threads...");
  12.         
  13. /*
  14. start() -> método que inicializa uma Thread.
  15. */
  16. thread1.start();
  17.         thread2.start();
  18.         thread3.start();
  19.         thread4.start();

  20.         System.out.println("\nThreads Inicializadas.");

  21.     }
  22. }

  23. class PrintThread extends Thread
  24. {
  25.     private int tempoDeEspera;

  26.     public PrintThread (String nome){
  27.         
  28.         super(nome);

  29.         tempoDeEspera = (int) (Math.random() * 5000 );

  30.         System.out.println("Nome: "+ getName() + " - Tempo de Espera: " + tempoDeEspera);
  31.     }

  32.     public void run(){
  33.         try{
  34.             System.out.println(getName() + " começando o tempo de espera...");
  35.             Thread.sleep(tempoDeEspera);
  36.         }
  37.         catch (InterruptedException ex){
  38.             System.out.println(ex.toString() );
  39.         }

  40.         //Imprime o nome do thread
  41.         System.out.println(getName() + " está sendo reativada.");
  42.     }
  43. }

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. package visao;

  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. import java.util.*;

  6. public class TimerTest {  
  7.     public static void main(String[] args) {  
  8.         JFrame f = new TimerTestFrame();
  9.         f.setVisible(true);
  10.     }
  11. }

  12. class TimerTestFrame extends JFrame {  
  13.     
  14.     public TimerTestFrame() {  
  15.         setSize(450, 300);
  16.         setTitle("TimerTest");

  17.         addWindowListener(new WindowAdapter()
  18.            {  public void windowClosing(WindowEvent e)
  19.               {  System.exit(0);
  20.               }
  21.            } );

  22.         Container c = getContentPane();
  23.         c.setLayout(new GridLayout(2, 3));
  24.         c.add(new ClockCanvas("Brasil", "GMT-2"));
  25.         c.add(new ClockCanvas("Taipei", "GMT+8"));
  26.         c.add(new ClockCanvas("Berlin", "GMT+1"));
  27.         c.add(new ClockCanvas("New York", "GMT-5"));
  28.         c.add(new ClockCanvas("Cairo", "GMT+2"));
  29.         c.add(new ClockCanvas("Bombay", "GMT+5"));
  30.     }
  31. }

  32. interface TimerListener {  
  33.     void timeElapsed(Timer t);
  34. }

  35. class Timer extends Thread{  
  36.     public Timer(int i, TimerListener t){  
  37.         target  = t;
  38.         interval = i;
  39.         setDaemon(true);
  40.     }

  41.     public void run(){  
  42.         try {  
  43.             while (!interrupted()) {  
  44.                 sleep(interval);
  45.                 target.timeElapsed(this);
  46.             }
  47.         }
  48.         catch(InterruptedException e) {}
  49.     }

  50.     private TimerListener target;
  51.     private int interval;
  52. }

  53. class ClockCanvas extends JPanel implements TimerListener{  
  54.     public ClockCanvas(String c, String tz){  
  55.         city = c;
  56.         calendar = new GregorianCalendar(TimeZone.getTimeZone(tz));
  57.         Timer t = new Timer(1000, this);
  58.         t.start();
  59.         setSize(125, 125);
  60.     }

  61.     public void paintComponent(Graphics g){  
  62.         super.paintComponent(g);
  63.         super.setBackground(Color.white);
  64.         g.drawOval(0, 0, 100, 100);
  65.         double hourAngle = 2 * Math.PI
  66.            * (seconds - 3 * 60 * 60) / (12 * 60 * 60);
  67.         double minuteAngle = 2 * Math.PI
  68.            * (seconds - 15 * 60) / (60 * 60);
  69.         double secondAngle = 2 * Math.PI
  70.            * (seconds - 15) / 60;
  71.         g.drawLine(50, 50, 50 + (int)(30
  72.            * Math.cos(hourAngle)),
  73.            50 + (int)(30 * Math.sin(hourAngle)));
  74.         g.drawLine(50, 50, 50 + (int)(40
  75.            * Math.cos(minuteAngle)),
  76.            50 + (int)(40 * Math.sin(minuteAngle)));
  77.         g.drawLine(50, 50, 50 + (int)(45
  78.            * Math.cos(secondAngle)),
  79.            50 + (int)(45 * Math.sin(secondAngle)));
  80.         g.drawString(city, 0, 115);
  81.     }

  82.     public void timeElapsed(Timer t){  
  83.         calendar.setTime(new Date());
  84.         seconds = calendar.get(Calendar.HOUR) * 60 * 60
  85.            + calendar.get(Calendar.MINUTE) * 60
  86.            + calendar.get(Calendar.SECOND);
  87.         repaint();
  88.     }

  89.     private int seconds = 0;
  90.     private String city;
  91.     private int offset;
  92.     private GregorianCalendar calendar;

  93.     private final int LOCAL = 16;
  94. }


xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. package visao;

  2. import modelo.ContaBancaria;
  3. import modelo.DepositoThread;
  4. import modelo.SaqueThread;

  5. public class UIBancoThread {
  6. public static void main(String[] args) {
  7. ContaBancaria cb = new ContaBancaria();
  8. DepositoThread t1 = new DepositoThread(cb, 100);
  9. SaqueThread t2 = new SaqueThread(cb, 100);
  10. DepositoThread t3 = new DepositoThread(cb, 100);
  11. SaqueThread t4 = new SaqueThread(cb, 100);
  12. t1.start();
  13. t2.start();
  14. t3.start();
  15. t4.start();
  16. }
  17. }

Classe ContaBancária:
  1. package modelo;

  2. public class ContaBancaria {
  3. private double saldo;

  4. public ContaBancaria() {
  5. super();
  6. // TODO Auto-generated constructor stub
  7. this.saldo = 0;
  8. }
  9. public double getSaldo(){
  10. return this.saldo;
  11. }
  12. public synchronized void deposito(double vlr){
  13. System.out.print("Depositando "+vlr);
  14. this.saldo += vlr;
  15. System.out.println(", novo saldo é "+this.getSaldo());
  16. notifyAll();
  17. }
  18. public synchronized void saque(double vlr) throws InterruptedException {
  19. while(saldo < vlr){
  20. System.out.println("Saldo insuficiente para saque!!!");
  21. wait();
  22. }
  23. System.out.print("Sacando "+vlr);
  24. this.saldo -= vlr;
  25. System.out.println(", novo saldo é "+this.getSaldo());
  26. }
  27. }


Classe DepositoThread:

  1. package modelo;

  2. public class DepositoThread extends Thread{

  3. private ContaBancaria conta;
  4. private double valor;
  5. private static final int REPETICOES = 10;
  6. private static final int DELAY = 10;
  7. public DepositoThread(ContaBancaria conta, double valor){
  8. this.conta = conta;
  9. this.valor = valor;
  10. }
  11. public void run(){
  12. try{
  13. for(int i=1; i<= REPETICOES && !isInterrupted(); i++){
  14. System.out.print(this.getName()+" => ");
  15. conta.deposito(valor);
  16. sleep(DELAY);
  17. }
  18. }
  19. catch(InterruptedException e){
  20. }
  21. }
  22. }
Classe Saque:
  1. package modelo;

  2. public class SaqueThread extends Thread{

  3. private ContaBancaria conta;
  4. private double valor;
  5. private static final int REPETICOES = 10;
  6. private static final int DELAY = 10;
  7. public SaqueThread(ContaBancaria conta, double valor){
  8. this.conta = conta;
  9. this.valor = valor;
  10. }
  11. public void run(){
  12. try{
  13. for(int i=1; i<= REPETICOES && !isInterrupted(); i++){
  14. System.out.print(this.getName()+" => ");
  15. conta.saque(valor);
  16. sleep(DELAY);
  17. }
  18. System.out.println("\n"+this.getName()+" Saldo final => "+conta.getSaldo()+"\n");
  19. }
  20. catch(InterruptedException e){
  21. }
  22. }
  23. }

O resultado da execução do código  UIBancoThread:



xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

  1. package visao;

  2. import modelo.MensagemThread;

  3. public class UIMensagemThread {

  4. public static void main(String[] args) {
  5. MensagemThread t1 = new MensagemThread("Bem-vindo!!!");
  6. MensagemThread t2 = new MensagemThread("Volte sempre!!!");
  7. t1.start();
  8. t2.start();
  9. }
  10. }

Classe MensagemThread:

  1. package modelo;

  2. import java.util.Date;

  3. public class MensagemThread extends Thread{

  4. private String frase;

  5. private static final int REPETICOES = 10;
  6. private static final int DELAY = 1000;

  7. public MensagemThread(String frase){
  8. this.frase = frase;
  9. }
  10. @Override
  11. public void run() {
  12. // TODO Auto-generated method stub
  13. super.run();
  14. try{
  15. for(int i=1; i<= REPETICOES && !isInterrupted(); i++){
  16. Date data = new Date();
  17. System.out.println(this.getName()+" => "+data+" "+frase);
  18. sleep(DELAY);
  19. }
  20. }
  21. catch(InterruptedException e){}
  22. }
  23. }

O resultado do código será:

No comments:

Post a Comment