Capítulo 6 Threads - sessão 10
- package visao;
- import modelo.Ex1MinhaThread;
- public class Ex1UsaThread {
- public static void main(String[] args) {
- System.out.println("****INICIO MAIN****");
- // 1) Para criar uma thread, deve-se instanciar um objeto da classe.
- // O construtor pode receber como parâmetro o nome da Thread.
- Ex1MinhaThread mt1 = new Ex1MinhaThread("Thread-1");
- Ex1MinhaThread mt2 = new Ex1MinhaThread("Thread-2");
- Ex1MinhaThread mt3 = new Ex1MinhaThread("Thread-3");
- // 2) Para colocá-la em execução, utiliza-se o método start()
- mt1.start();
- mt2.start();
- mt3.start();
- // As threads são finalizadas quando seu método run() chega ao fim
- System.out.println ("****FIM MAIN****");
- }
- }
Abaixo temos a classe Ex1MinhaThread.java:
- package modelo;
- // 1) herança da classe Thread
- // Classe Thread: pertence ao java.lang
- public class Ex1MinhaThread extends Thread{
- public Ex1MinhaThread( String s ){
- this.setName(s);
- }
- // 2) implementar o método run, que será executado quando start for invocado
- @Override // Uma thread termina quando seu método run() chega ao fim
- public void run () {
- System.out.println ("Início: " + getName());
- for (int i = 0; i < 10; i++)
- System.out.println ( getName() + "-" + i );
- System.out.println ("Fim: " + getName());
- }
- }
- /* Operações sobre Threads
- - interrupt(): interrompe a thread;
- No método run, deve-se testar se a thread está
- interrompida através do método isInterrupted(), para
- fazer o tratamento final dos recursos utilizados pela thread;
- - sleep(long): suspende a thread por um período determinado (ms);
- Se a thread for interrompida enquanto estiver suspensa, a
- exceção InterruptedException é lançada pelo método sleep;
- - join() ou join(long): espera até a thread terminar;
- Uma thread pode esperar pela finalização de outra por
- meio de uma chamada ao método join();
- - yield(): suspende a thread corrente, permitindo que
- outras sejam executadas;
- */
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
- package visao;
- import modelo.Ex4DadoA;
- import modelo.Ex4P1;
- import modelo.Ex4P2;
- public class Ex4UsaDadoA {
- public static void main(String[] args) {
- Ex4DadoA a = new Ex4DadoA( 5 ) ;
- Ex4P1 ta1 = new Ex4P1( a ) ;
- Ex4P2 ts2 = new Ex4P2( a ) ;
- Ex4P1 ta3 = new Ex4P1( a ) ;
- Ex4P2 ts4 = new Ex4P2( a ) ;
- ta1.start() ;
- ts2.start() ;
- ts4.start() ;
- ta3.start() ;
- }
- }
O exemplo abaixo é da classe Ex4DadoA que está sendo instanciada na linha 10 do programa acima:
- package modelo;
- public class Ex4DadoA {
- private int a ;
- public Ex4DadoA( int ini ){
- a = ini ;
- }
- // synchronized: impede acesso ao mesmo objeto
- public synchronized void add( int v ){
- a = a + v ;
- System.out.println( "Somou 1 => a = " + a ) ;
- }
- // synchronized: impede acesso ao mesmo objeto
- public synchronized void sub( int v ){
- a = a - v ;
- System.out.println( "Subtraiu 1 => a = " + a ) ;
- }
- }
O exemplo abaixo é da classe Ex4P1 que está sendo instanciada na linha 12 do programa Ex4UsaDadoA:
- package modelo;
- public class Ex4P1 extends Thread {
- private Ex4DadoA a ;
- public Ex4P1( Ex4DadoA a ){
- this.a = a ;
- }
- public void run(){
- a.add(1);
- }
- }
O exemplo abaixo é da classe Ex4P2 que está sendo instanciada na linha 12 do programa Ex4UsaDadoA:
- package modelo;
- public class Ex4P2 extends Thread{
- private Ex4DadoA a ;
- public Ex4P2( Ex4DadoA a ){
- this.a = a ;
- }
- public void run(){
- a.sub(1);
- }
- }
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- package visao;
- import java.util.*;
- public class ExemploThreads {
- public static void main(String args[]) {
- TestThread t1, t2, t3;
- t1 = new TestThread("Thread 01",(int)(Math.random() * 2000));
- t2 = new TestThread("Thread 02",(int)(Math.random() * 2000));
- t3 = new TestThread("Thread 03",(int)(Math.random() * 2000));
- t1.setPriority(1);
- t3.setPriority(10);
- t1.start();
- t2.start();
- t3.start();
- try {
- t1.join();
- t2.join();
- t3.join();
- } catch (InterruptedException e) { }
- }
- }
- class TestThread extends Thread {
- private int tempoDeEspera;
- public TestThread(String s, int tpEspera) {
- super ( s );
- tempoDeEspera = tpEspera;
- }
- public void run() {
- try {
- sleep(tempoDeEspera);
- } catch (InterruptedException e) { }
- System.out.println( getName() + " - " + new Date());
- }
- }
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- package visao;
- public class ThreadTest
- {
- public static void main(String[] args)
- {
- PrintThread thread1, thread2, thread3, thread4;
- thread1 = new PrintThread("Thread 01");
- thread2 = new PrintThread("Thread 02");
- thread3 = new PrintThread("Thread 03");
- thread4 = new PrintThread("Thread 04");
- System.out.println("\nInicializando Threads...");
- /*
- start() -> método que inicializa uma Thread.
- */
- thread1.start();
- thread2.start();
- thread3.start();
- thread4.start();
- System.out.println("\nThreads Inicializadas.");
- }
- }
- class PrintThread extends Thread
- {
- private int tempoDeEspera;
- public PrintThread (String nome){
- super(nome);
- tempoDeEspera = (int) (Math.random() * 5000 );
- System.out.println("Nome: "+ getName() + " - Tempo de Espera: " + tempoDeEspera);
- }
- public void run(){
- try{
- System.out.println(getName() + " começando o tempo de espera...");
- Thread.sleep(tempoDeEspera);
- }
- catch (InterruptedException ex){
- System.out.println(ex.toString() );
- }
- //Imprime o nome do thread
- System.out.println(getName() + " está sendo reativada.");
- }
- }
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- package visao;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- import java.util.*;
- public class TimerTest {
- public static void main(String[] args) {
- JFrame f = new TimerTestFrame();
- f.setVisible(true);
- }
- }
- class TimerTestFrame extends JFrame {
- public TimerTestFrame() {
- setSize(450, 300);
- setTitle("TimerTest");
- addWindowListener(new WindowAdapter()
- { public void windowClosing(WindowEvent e)
- { System.exit(0);
- }
- } );
- Container c = getContentPane();
- c.setLayout(new GridLayout(2, 3));
- c.add(new ClockCanvas("Brasil", "GMT-2"));
- c.add(new ClockCanvas("Taipei", "GMT+8"));
- c.add(new ClockCanvas("Berlin", "GMT+1"));
- c.add(new ClockCanvas("New York", "GMT-5"));
- c.add(new ClockCanvas("Cairo", "GMT+2"));
- c.add(new ClockCanvas("Bombay", "GMT+5"));
- }
- }
- interface TimerListener {
- void timeElapsed(Timer t);
- }
- class Timer extends Thread{
- public Timer(int i, TimerListener t){
- target = t;
- interval = i;
- setDaemon(true);
- }
- public void run(){
- try {
- while (!interrupted()) {
- sleep(interval);
- target.timeElapsed(this);
- }
- }
- catch(InterruptedException e) {}
- }
- private TimerListener target;
- private int interval;
- }
- class ClockCanvas extends JPanel implements TimerListener{
- public ClockCanvas(String c, String tz){
- city = c;
- calendar = new GregorianCalendar(TimeZone.getTimeZone(tz));
- Timer t = new Timer(1000, this);
- t.start();
- setSize(125, 125);
- }
- public void paintComponent(Graphics g){
- super.paintComponent(g);
- super.setBackground(Color.white);
- g.drawOval(0, 0, 100, 100);
- double hourAngle = 2 * Math.PI
- * (seconds - 3 * 60 * 60) / (12 * 60 * 60);
- double minuteAngle = 2 * Math.PI
- * (seconds - 15 * 60) / (60 * 60);
- double secondAngle = 2 * Math.PI
- * (seconds - 15) / 60;
- g.drawLine(50, 50, 50 + (int)(30
- * Math.cos(hourAngle)),
- 50 + (int)(30 * Math.sin(hourAngle)));
- g.drawLine(50, 50, 50 + (int)(40
- * Math.cos(minuteAngle)),
- 50 + (int)(40 * Math.sin(minuteAngle)));
- g.drawLine(50, 50, 50 + (int)(45
- * Math.cos(secondAngle)),
- 50 + (int)(45 * Math.sin(secondAngle)));
- g.drawString(city, 0, 115);
- }
- public void timeElapsed(Timer t){
- calendar.setTime(new Date());
- seconds = calendar.get(Calendar.HOUR) * 60 * 60
- + calendar.get(Calendar.MINUTE) * 60
- + calendar.get(Calendar.SECOND);
- repaint();
- }
- private int seconds = 0;
- private String city;
- private int offset;
- private GregorianCalendar calendar;
- private final int LOCAL = 16;
- }
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- package visao;
- import modelo.ContaBancaria;
- import modelo.DepositoThread;
- import modelo.SaqueThread;
- public class UIBancoThread {
- public static void main(String[] args) {
- ContaBancaria cb = new ContaBancaria();
- DepositoThread t1 = new DepositoThread(cb, 100);
- SaqueThread t2 = new SaqueThread(cb, 100);
- DepositoThread t3 = new DepositoThread(cb, 100);
- SaqueThread t4 = new SaqueThread(cb, 100);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
Classe ContaBancária:
- package modelo;
- public class ContaBancaria {
- private double saldo;
- public ContaBancaria() {
- super();
- // TODO Auto-generated constructor stub
- this.saldo = 0;
- }
- public double getSaldo(){
- return this.saldo;
- }
- public synchronized void deposito(double vlr){
- System.out.print("Depositando "+vlr);
- this.saldo += vlr;
- System.out.println(", novo saldo é "+this.getSaldo());
- notifyAll();
- }
- public synchronized void saque(double vlr) throws InterruptedException {
- while(saldo < vlr){
- System.out.println("Saldo insuficiente para saque!!!");
- wait();
- }
- System.out.print("Sacando "+vlr);
- this.saldo -= vlr;
- System.out.println(", novo saldo é "+this.getSaldo());
- }
- }
Classe DepositoThread:
- package modelo;
- public class DepositoThread extends Thread{
- private ContaBancaria conta;
- private double valor;
- private static final int REPETICOES = 10;
- private static final int DELAY = 10;
- public DepositoThread(ContaBancaria conta, double valor){
- this.conta = conta;
- this.valor = valor;
- }
- public void run(){
- try{
- for(int i=1; i<= REPETICOES && !isInterrupted(); i++){
- System.out.print(this.getName()+" => ");
- conta.deposito(valor);
- sleep(DELAY);
- }
- }
- catch(InterruptedException e){
- }
- }
- }
Classe Saque:
- package modelo;
- public class SaqueThread extends Thread{
- private ContaBancaria conta;
- private double valor;
- private static final int REPETICOES = 10;
- private static final int DELAY = 10;
- public SaqueThread(ContaBancaria conta, double valor){
- this.conta = conta;
- this.valor = valor;
- }
- public void run(){
- try{
- for(int i=1; i<= REPETICOES && !isInterrupted(); i++){
- System.out.print(this.getName()+" => ");
- conta.saque(valor);
- sleep(DELAY);
- }
- System.out.println("\n"+this.getName()+" Saldo final => "+conta.getSaldo()+"\n");
- }
- catch(InterruptedException e){
- }
- }
- }
O resultado da execução do código  UIBancoThread:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- package visao;
- import modelo.MensagemThread;
- public class UIMensagemThread {
- public static void main(String[] args) {
- MensagemThread t1 = new MensagemThread("Bem-vindo!!!");
- MensagemThread t2 = new MensagemThread("Volte sempre!!!");
- t1.start();
- t2.start();
- }
- }
Classe MensagemThread:
- package modelo;
- import java.util.Date;
- public class MensagemThread extends Thread{
- private String frase;
- private static final int REPETICOES = 10;
- private static final int DELAY = 1000;
- public MensagemThread(String frase){
- this.frase = frase;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- super.run();
- try{
- for(int i=1; i<= REPETICOES && !isInterrupted(); i++){
- Date data = new Date();
- System.out.println(this.getName()+" => "+data+" "+frase);
- sleep(DELAY);
- }
- }
- catch(InterruptedException e){}
- }
- }
O resultado do código será:









 
No comments:
Post a Comment