Você está na página 1de 235

CE-703

Programação Orientada a Objetos para


Sistemas Embutidos

Prof. Paulo André Castro pauloac@ita.br


www.comp.ita.br/~pauloac Sala 110, IEC-ITA
Linguagens de Programação em
Sistemas Embutidos
Assembly
Linguagens de Alto nível
C
Linguagens Orientadas a Objetos
Ada, C++, Java
As linguagens OO já correspondem a maioria das aplicações em Sistemas Embutidos
Em sistemas embutidos de aviação civil (regulados pelo DO-178), há questões em
aberto sobre certificação de software orientado a objetos (C++/ Java) , entretanto:
Há compiladores Ada validados para utilização em aplicações de missão crítica
“DO-178C,is an upcoming document that will replace DO-178B to be the primary document by which the
certification authorities … and it is due to be finalized in 2011”
Entre os objetivos do DO-178C está… addressing object-oriented software and the conditions under which
it can be used

No futuro próximo, é bastante provável que linguagens OO sejam usadas com


freqüência inclusive em sistemas embutidos de missão crítica (aviação civil)

Paulo André Castro CE-703 / ITA


Camadas de um Sistema Completo

Paulo André Castro CE-703 / ITA


Arquitetura de Software Típica em
Dispositivos Móveis

Paulo André Castro CE-703 / ITA


Processo de Desenvolvimento de
Software Embutido

Paulo André Castro CE-703 / ITA


Java para
Sistemas
Embutidos

Paulo André Castro CE-703 / ITA


Paulo André Castro CE-703 / ITA
Introdução OO
Programação Estruturada x Programação Orientada a
Objetos
Modelagem com base no conceito de módulo ou sub-programa
Modelagem com base no conceito de classe e seus
relacionamentos
Linguagens Orientadas a Objetos
Simula, SmallTalk
C++, C#, (VB?), etc.
Java

Paulo8André Castro CE-703 / ITA


Programação Estrurada

dados dados
acessa globais
globais
invoca
internos ou
externos

Proc2
dados
locais
dados
Proc

Proc Proc
Principal

Paulo9André Castro CE-703 / ITA


Programação Orientada a Objetos
dados
dados
classe
relacionamento classe
----------
----------
----------

Dados de
cada classe/ dados
objeto
classe Classes contém
procedimentos
(métodos)

acessa invoca

Paulo10André Castro CE-703 / ITA


Sumário
Introdução
Conceitos Básicos
Nomenclatura básica em OO
Variáveis e Instâncias
Métodos
Encapsulamento
Herança e Polimorfismo
Introdução a linguagem Java

Paulo11André Castro CE-703 / ITA


Conceitos básicos de OO
Classe: um categoria de entidades (“coisas”)
Corresponde a um tipo, ou coleção, ou conjunto de entidades
afins
Objeto: Uma entidade com existência física que pertence
a um determinado conjunto de entidades afins (classe)

Paulo12André Castro CE-703 / ITA


Exemplos de Classe e Objeto
Classes:
Carro, Avião, Pessoa

Objetos:
Carro: Porsche 910 Placa XXXX
Avião: Boeing 737-300 Prefixo: PY-XXX
Pessoa: José da Silva CPF: XXXXXXX

Paulo13André Castro CE-703 / ITA


Classes x Tipos de Dados

Uma classe é um tipo definido pelo usuário que contém uma estrutura
de dados e um conjunto de operações que atuam sobre estes dados
Analogamente, é o mesmo que o tipo inteiro significa para as variáveis
declaradas como inteiros: acesso a valores através de operações
A classe encapsula dados e operações e controla o acesso a estas
propriedades

Data
públicos/privativos int dia,mes,ano
alteraData()

Paulo14André Castro CE-703 / ITA


UML
Unified Modeling Language
Linguagem Unificada de Modelagem
Linguagem Visual de Modelagem Orientada a Objetos
Referência: The Unified Modeling Language User Guide; G.
Booch, J. Rumbaugh, I. Jacobson. ACM Press. 2000

Paulo15André Castro CE-703 / ITA


UML: notações de classes
Nome

Nome Atributos

Operações
String
Nome
itálico: abstrata
Atributos operações não
Date implementadas
Operações

Paulo16André Castro CE-703 / ITA


Exemplo em UML - Herança

Paulo17André Castro CE-703 / ITA


Exemplo em UML – Está correto ?

Paulo André Castro CE-703 / ITA


18
Exemplo de Orientação a Objetos
- Java
Classe
public class Pessoa {
private int idade;
private boolean sexo; // Verdadeiro para mulheres
private boolean ehResponsavel() {
if(idade>21 )
return true;
if(idade>18 && !sexo)
return true;
else
return false;
}
public Pessoa(String nome, int id, boolean sex) {Nome=nome; idade=id; sexo=sex; }
}
}..........................................................

Paulo André Castro CE-703 / ITA


Mais em Orientação a Objetos

Herança
Uma classe pode utilizar métodos e atributos de outras
classes sem a necessidade de re-escrever ou copiar nada
através do mecanismo de Herança
public class Funcionario extends Pessoa {
double salario;
int id;
public double getSalario() {
return salario;
}}

Paulo André Castro CE-703 / ITA


Classes e sub-classes
Classe, classe-pai, super-classe, classe base:
Carro
Motor
Avião
Sub-classe, classe-filha, classe derivada
Carro: Porsche 910
Motor: Ford 16V
Avião: Boeing 737

Paulo21André Castro CE-703 / ITA


Relação de Herança
O filho herda todas as características do pai
Comportamento: funções
Atributos: valores

Em linguangens OO, geralmente há meios de restringir o


que será ou não herdado

Paulo22André Castro CE-703 / ITA


Exemplo de Herança Múltipla

Paulo23André Castro CE-703 / ITA


Relação Agregação (Todo-Parte)
Uma classe é composta por uma ou mais classes:
Exemplos:
Carro e Motor
Avião e Motor
Pessoa e Braço

Paulo24André Castro CE-703 / ITA


Agregação em UML

Paulo25André Castro CE-703 / ITA


Composição: Tipo especial de Agregação
Parte pertence a apenas um todo e tem tempo de vida igual ao todo

Paulo26André Castro CE-703 / ITA


Outras Relações: Associação

Paulo27André Castro CE-703 / ITA


Outras Relações: Associação com
Qualificação

Paulo28André Castro CE-703 / ITA


Métodos e Atributos
Classes podem ter vários métodos e atributos
Método: define um comportamento de uma classe
Atributo: define uma informação a ser mantida por cada
instância de uma classe
Escopo
Escopo de Classe:
Ex. Boeing 737 atributo: número de motores
Escopo de Objeto (“Instância”)
Ex. Boeing 737 atributo: número de assentos

Paulo29André Castro CE-703 / ITA


Encapsulamento
Encapsulamento: É a capacidade de “esconder” parte do
código e dos dados do restante do programa
Pode-se definir um grau de visibilidade aos métodos e
atributos de cada Classe.
Há vários graus de visibilidade mas todas as linguagens
implementam pelo menos os seguintes:
Público: Todos podem acessar (ler e escrever)
Privado: Apenas a própria classe pode acessar.

Paulo30André Castro CE-703 / ITA


Polimorfismo
Um mesmo comando enviado para objetos diferentes
gera (ou pode gerar) ações diferentes.
Exemplo:
Comando: Mover
Carro
Avião
Pessoa

Paulo31André Castro CE-703 / ITA


Exemplo de Orientação a Objetos
– classe Pessoa
Arquivo: Pessoa.java
public class Pessoa {
private int idade;
private boolean sexo; // Verdadeiro para mulheres
private boolean ehResponsavel() {
if(idade>21 )
return true;
if(idade>18 && !sexo)
return true;
else
return false;
}
public Pessoa(String nome, int id, boolean sex) {Nome=nome; idade=id; sexo=sex; }
}
}

Paulo32André Castro CE-703 / ITA


Exemplo de Orientação a Objetos
– subclasse Casado
Arquivo: Casado.java
public class Casado extends Pessoa {
public boolean ehResponsavel() {
return true;
}
public Casado(String nome,int id,boolean sexo) {
super(nome,idade,sexo);
}}

Paulo33André Castro CE-703 / ITA


Polimorfismo – Código Java

public class ExemploPessoa {


public static void main(String[] args) {
Casado casado=new Casado(“Zé”,17,false);
Pessoa cidadao=new Pessoa(“Maria”,18,true);
Pessoa[] trabalhador= new Pessoa[2];
trabalhador[0]=casado;
trabalhador[1]=cidadao;
for(int i=0; i<2; i++) {
String aux;
if(trabalhador[i].ehResponsavel())
aux.strcpy(trabalhador[i].Nome+”é responsável”);
else
aux.strcpy(trabalhador[i].Nome+ “não é responsável.“);
System.out.println(aux);
}
}
}
Qual o resultado da execução?
Paulo André Castro CE-703 / ITA
Mais em Orientação a Objetos
Alterando comportamento nas classes filhas.
Sobrescrever método.
public class Casado extends Pessoa {
public boolean ehResponsavel() {
return true;
}
public Casado(String nome,int id,boolean sexo) {
super(nome,idade,sexo);
}}

Paulo35André Castro CE-703 / ITA


Mais em Orientação a Objetos –
Sobrecarga de Métodos
Sobrecarga permite a existência de vários métodos de mesmo nome,
porém com assinaturas levemente diferentes ou seja variando no
número e tipo de argumentos e no valor de retorno
public Logaritmo {
……
public double log(double x) {
return Math.log(x);
}
public double log(double x, double b) {
return (Math.log(x)/Math.log(b));
}
}

Paulo36André Castro CE-703 / ITA


Métodos Abstratos
Métodos abstratos não tem implementação, porém
obrigam as classes filhas a realizarem esta implementação.
Útil para criar padronizações para as classes derivadas

Se uma classe tem um (ou mais) métodos abstratos


torna-se uma classe abstrata e não pode ser instanciada

Exemplo:
Avião e o método Mover

Paulo37André Castro CE-703 / ITA


Herança e Interfaces
Herança Múltipla: quando uma classe pode herdar
métodos e atributos de várias classes
Não existe herança múltipla em Java, para evitar erros e
diminuir a complexidade da programação
Uma classe pode herdar apenas de uma outra classe
Todas as classes herdam da classe Object
Classe totalmente abstrata: Interface

Paulo André Castro CE-703 / ITA


Exemplo - Java
public class Ator extends Pessoa{
public String contrato;
/* campos herdados
class Pessoa{ public String nome;
public String nome; public char sexo;
public char sexo; public Date dataNasc; */
public Data dataNasc; -----}
---- public class Aluno extends Pessoa{
} public long matric;
/* campos herdados
public String nome;
public char sexo;
public Data dataNasc; */
-----}

Paulo39André Castro CE-703 / ITA


Interface
Interface: Contrato(s) que uma classe deve respeitar. Isto
é, um conjunto de métodos que a classe não pode deixar
de implementar.
interface Veiculo {
void mover();
double velocidade;
}

Paulo40André Castro CE-703 / ITA


Herança e Interfaces
Uma classe em Java pode implementar várias interfaces

public class Class1 extends Class2 implements


Interface1,Interface2,Interface3 {
......
....
}

Paulo41André Castro CE-703 / ITA


Outras Relações: Realização

Paulo42André Castro CE-703 / ITA


Resumo até agora
Componentes de uma classe
Métodos
Atributos(variáveis)
Relações
Relações entre Classes
Herança
Agregação
Associação
Realização(Classe/Inteface)

Paulo43André Castro CE-703 / ITA


Sumário
Introdução
Conceitos Básicos
Nomenclatura básica em OO
Variáveis e Instâncias
Métodos
Construtores
Herança e Polimorfismo
Introdução a linguagem Java
Primeiros Programas
Fundamentos
Tratamento de Erros
Coleções

Paulo44André Castro CE-703 / ITA


Java x C++

Paulo45André Castro CE-703 / ITA


Criando Programas java

Paulo46André Castro CE-703 / ITA


Exemplo

Paulo47André Castro CE-703 / ITA


Exemplo de Orientação a Objetos
- Java
Classe
public class Pessoa {
private int idade; private String nome;
private boolean sexo; // Verdadeiro para mulheres
private boolean ehResponsavel() {
if(idade>21 )
return true;
if(idade>18 && !sexo)
return true;
else
return false;
}
public Pessoa(String n, int id, boolean sex) {
nome=n; idade=id; sexo=sex;
}
}..........................................................

Paulo André Castro CE-703 / ITA


Criando Classes em Java
Convenção de Nomes em Java
Classes iniciam com letras maiúsculas
Métodos, atributos e variáveis locais iniciam com minúsculas
Declaração de Classes
public class MyClasse {
......
}
Criando Objetos a partir de Classes
Uso do “new”

Paulo49André Castro CE-703 / ITA


Orientação a Objetos em Java
Instâncias
String teste=new String(60);
String teste2=“Isto é um teste”;
ServerSocket servidor= new ServerSocket(25);
Construtores e destrutores
Os construtores são similares ao C++
Não há destrutores em Java.

Paulo André Castro CE-703 / ITA


Exemplo de Orientação a Objetos - Java
Objetos
Pessoa a=new Pessoa(“Joao”,25);
Pessoa b= new Pessoa(“Ana”,23);
Pessoa c=new Pessoa(“Carla”,28);
d=b;
Atributos de uma classe
a.idade == ?
d.nome = ?

Paulo51André Castro CE-703 / ITA


Formato de uma Definição de
Classe em Java

Paulo52André Castro CE-703 / ITA


Acessando variáveis de instância
Use um ponto entre o nome da variável e o campo
objectName.fieldName;
Por exemplo, usando a classe Point da biblioteca Java
Point p=new Point(2,3); //criação de objeto p
int x2= p.x*p.x; // x2 é 4
int xPlusY=p.x+p.y; // xPlusY é 5
p.x=3;
x2=p.x* p.x; // x2 agora é 9

Dentro de um objeto, seus métodos podem acessar as


variáveis de instância (e de Classe) sem utilizar o ponto

Paulo53André Castro CE-703 / ITA


Exemplo – Orientado a Objetos?

Paulo54André Castro CE-703 / ITA


Exemplos

Paulo55André Castro CE-703 / ITA


Resultado

Paulo56André Castro CE-703 / ITA


Problemas na Modelagem?
Código específico a uma classe está escrito apenas nesta
classe?

Paulo57André Castro CE-703 / ITA


Métodos: Exemplo

Paulo58André Castro CE-703 / ITA


Exemplo (cont.)

Paulo59André Castro CE-703 / ITA


Métodos Especiais: Construtores
Construtores são métodos de uma classe que tem o
mesmo nome desta classe e são chamados quando da
criação de um objeto desta classe.
São usados para “inicializar” um objeto
São chamados apenas através de um comando “new”
Java provê automaticamente um construtor sem parâmetros, caso
nenhum construtor seja declarado explicitamente
Por isso, podemos utilizar: Ship s1=new Ship(); Mesmo sem criar um
construtor Ship()

Paulo60André Castro CE-703 / ITA


Métodos Especiais: Construtores (2)

Paulo61André Castro CE-703 / ITA


Métodos Especiais: Construtores (3)

Paulo62André Castro CE-703 / ITA


Métodos Especiais: Construtores (4)

Paulo63André Castro CE-703 / ITA


A variável especial: this

Paulo64André Castro CE-703 / ITA


Destrutores
Não há destrutores em Java
Ao contrário de C++
Garbage Collector
Coletor de lixo: Faz a limpeza (remoção da memória) de
váriaveis que não serão mais utilizadas pelo programa.
Pode ser chamado através de :
System.gc();

Paulo65André Castro CE-703 / ITA


Convenções e Boas Práticas em OO
Resumo

Código referente exclusivamente a uma classe deve ficar


dentro desta classe
Uma classe deve ter o menor número possível de métodos
públicos, mas deve ter pelo menos um método público
É uma boa prática evitar variáveis públicas. Prefira utilizar
métodos para acessar as variáveis. Os métodos get e set.
Use métodos construtores para inicializar objetos

Paulo66André Castro CE-703 / ITA


Convenções e Boas Práticas em OO
Resumo
Classes devem iniciar com letras maiusculas, métodos,
atributos e variáveis com letras minúsculas
Métodos devem ter um tipo de retorno ou “void”
Acesse atributos através de objectName.fieldName
Acesse métodos através de objectName.methodName()
Métodos estáticos não precisam de instâncias da
classe
Construtores são métodos especiais sem tipo de
retorno

Paulo67André Castro CE-703 / ITA


Convenções e características em Java
Resumo
A referência this aponta para o objeto atual
Java faz seu próprio gerenciamento de memória e
portanto não requer destrutores
Java permite herança simples e o uso de interfaces
As classes abstratas e interfaces não podem ser
instanciadas
Uma classe Java pode implementar várias interfaces

Paulo68André Castro CE-703 / ITA


Fundamentos de Programação Java

Comandos
Sintaxe
Estrutura
Exemplos

Paulo69André Castro CE-703 / ITA


Fundamentos de Programação Java
Início e Fim de Blocos de Comandos
“{ “ e “}”
comandos if, if-else, while, do-while, for e switch-case são
idênticos ao C/ C++
Comando break <label>;

Paulo André Castro CE-703 / ITA


Tipos básicos de Variáveis

T ip o T am anho
b yte 1 b yte s
sh o rt 2 b yte s
in t 4 b yte s
lo n g 8 b yte s
flo a t 4 b yte s
d o u b le 8 b yte s
char 2 b yte s
b o o le a n 1 b it

Paulo André Castro CE-703 / ITA


Variáveis
Declaração
int inteiro; char letra;
byte apenasUmByte;
Declaração e Inicialização
float saldoConta=0.0;
boolean serOuNaoSer=false;

Paulo André Castro CE-703 / ITA


Tipos Complexos
int[] arrayInteiro= new int[40];
char sTexto[]= new char[60]; // use String’s
Classe String
String s=new String(“isto e uma string”);
String s2=“isto e outra string”;
String c=s+s2;
System.out.println(“S=”+s+”S2=”+s2+”c=”+c);

Paulo André Castro CE-703 / ITA


Tipos Complexos

Paulo74André Castro CE-703 / ITA


Exemplo

Paulo75André Castro CE-703 / ITA


Exemplo

Paulo76André Castro CE-703 / ITA


Comandos...
Comando := Comando_simples | Comando_composto |
Comando_condicional | Comando_iterativo | Comando_de_seleção

Comando_simples := Comando_de_atribuição | Comando_de_entrada


| Comando_de_saída | Chamada_de_subprograma | Comando_vazio

Comando_vazio := ;

Comando_composto := { Comando Comando . . . . . Comando


}

Paulo77André Castro CE-703 / ITA


Comandos...
Comando_condicional := if ( Expressão ) Comando_1
| if ( Expressão ) Comando_1 else Comando_2

Comando_iterativo := Comando_while | Comando_do |


Comando_for

Paulo78André Castro CE-703 / ITA


Comando de Seleção em Java
switch ( expressão ) {
case V11:
case V12:
.
.
case V1m: lista de comandos; break;
case V21:
case V22:
.
.
case V2n: lista de comandos; break;
.
.
case Vip: lista de comandos; break;
default: lista de comandos;
}

Paulo79André Castro CE-703 / ITA


Comandos...
Comando atribuição condicional
Forma: Expr1 ? Expr2 : Expr3
Calcula-se Expr1;
Se o valor for Verdadeiro, calcula-se o valor de Expr2, que
será o valor da expressão condicional;
Se o valor for Falso, calcula-se o valor de Expr3, que será o
valor da expressão condicional.

Paulo80André Castro CE-703 / ITA


Comandos de repetição

Paulo81André Castro CE-703 / ITA


Comandos Iterativos...
Comandos for e while versus Comando do-while
Comando break: Saída anormal de um comando iterativo ou comando de
seleção mais interno.

while ( ......... ) {
.........
if ( ......... ) break;
if ( ......... ) continue;
.........
}
......... /* Proximo comando a ser executado depois do break */
.........
Comando continue: encerra a iteração corrente e inicia a iteração seguinte.

Paulo82André Castro CE-703 / ITA


Exemplo - while

Paulo83André Castro CE-703 / ITA


Exemplo – do/while

Paulo84André Castro CE-703 / ITA


Exemplo - for

Paulo85André Castro CE-703 / ITA


Percorrendo todos os elementos
de um array

Paulo86André Castro CE-703 / ITA


Percorrendo todos os elementos
de um array

Paulo87André Castro CE-703 / ITA


Comando condicional - if

Paulo88André Castro CE-703 / ITA


Expressões Condicionais

Paulo89André Castro CE-703 / ITA


Exemplos

Paulo90André Castro CE-703 / ITA


Comparação de Strings

Paulo91André Castro CE-703 / ITA


Criando Arrays

Paulo92André Castro CE-703 / ITA


Arrays de várias dimensões

Paulo93André Castro CE-703 / ITA


Exemplo

Paulo94André Castro CE-703 / ITA


Resultado

Paulo95André Castro CE-703 / ITA


Tratamento de Erros: Tradicional
O tratamento de erros em linguagens sem Exceções, gera
um código “sujo” com código tratamento de erro:
ret=funcao1();
if(ret==ERRO)
//Trata erro
ret=funcao2();
if(ret==ERRO)
//Trata Erro 2

Paulo96André Castro CE-703 / ITA


Tratamento de Erros: Exceções
Em Java, o sistema de tratamento de erros é baseado
exceções
Exceções devem ser tratados em blocos try/catch
Quando ocorre uma exceção esta é direcionada para o
correspondente catch
Formato:

97
Diagrama Simplicado de Exceções

Paulo98André Castro CE-703 / ITA


Try-catch
Um bloco try pode ter associados vários blocos catch

A exceção será tratado pelo bloco catch mais específico


Caso não seja encontrado algum apropriado, a exceção
será direcionada para blocos try mais externos
Caso não seja encontrado nenhum try apropriado dentro do
método, este irá jogar a exceção

99
Um exemplo de Try-catch

Paulo100
André Castro CE-703 / ITA
A cláusula finally
Ao final de um conjunto de blocos catch pode-se,
opcionalmente, incluir uma cláusula finally. Caso
nenhum bloco catch, seja executado o finally será
sempre executado

101
Jogando exceções

Paulo102
André Castro CE-703 / ITA
Estruturas de Dados no Java 2

Paulo103
André Castro CE-703 / ITA
Collection Interfaces

Paulo104
André Castro CE-703 / ITA
Duas Estruturas de Dados Muito
Úteis
Vector
Um array de Object de tamanho variável
Tempo para acessar um objeto é independente da sua posição na
lista
No jdk 1.2 ou superior, pode-se utilizar ArrayList
ArrayList não é sincronizado (thread-safe), por isso tende a ser
mais rápido
Hashtable
Armazena pares: nome-valor como Object
Valores não podem ser nulos
No jdk 1.2 ou superior, pode-se utilizar HashMap
HashMap não é sincronizado (thread-safe), por isso tende a ser
mais rápido

Paulo105
André Castro CE-703 / ITA
Métodos úteis em Vector

Paulo106
André Castro CE-703 / ITA
Utilizando Vector

Paulo107
André Castro CE-703 / ITA
Métodos úteis em Hashtable

Paulo108
André Castro CE-703 / ITA
Exemplo de Uso de um Hashtable
import java.util.Hashtable;

public class ExemploHashtable {


public static void main(String[] args) {
Hashtable numbers = new Hashtable();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
String key="three";
Integer n = (Integer)numbers.get(key);
if (n != null) {
System.out.println(key+" = " + n);
}
}
}

Paulo109
André Castro CE-703 / ITA
Resultado
>three = 3

Paulo110
André Castro CE-703 / ITA
Exemplo de Uso de uma Coleção
Vector
import java.util.Iterator;
import java.util.Vector;

public class Colecoes {

public static void main(String[] args) {


Vector vetStrings=new Vector();
for(int i=1;i<=5;i++)
vetStrings.add("Linha "+i);
//Laços de Iteração
for (Iterator iter = vetStrings.iterator(); iter.hasNext();) {
String element = (String) iter.next();
System.out.println(element);
}
}
}
Paulo111
André Castro CE-703 / ITA
Resultado
>Linha 1
Linha 2
Linha 3
Linha 4
Linha 5

Paulo112
André Castro CE-703 / ITA
Classes Genéricas no JDK 5.0
Classe genéricas: classes que podem ser parametrizadas
para trabalharem sobre classes específicas
Tipos parametrizáveis: (Design Patterns, GoF)
Templates: C++
Classes genéricas: Java,C#

Paulo113
André Castro CE-703 / ITA
Avanços em Collections no JDK 5.0
Coleções genéricas:
Vector<String> vetStrings=new Vector<String>();
Laços de Iteração Aprimorados
for(String element: vetStrings) {
System.out.println(element);
}

Paulo114
André Castro CE-703 / ITA
Exemplo de Uso de uma Coleção
Genérica
import java.util.Vector;

public class ColecoesGenericas {

public static void main(String[] args) {

Vector<String > vetStrings=new Vector<String>();


for(int i=1;i<=5;i++)
vetStrings.add("Linha "+i);
//Laços de Iteração Aprimorados
for(String element: vetStrings) {
System.out.println(element);
}
}
}

Paulo115
André Castro CE-703 / ITA
Resultado
>Linha 1
Linha 2
Linha 3
Linha 4
Linha 5

Paulo116
André Castro CE-703 / ITA
HashTable Genérico
import java.util.Hashtable;

public class ExemploHashtableGenerico {


public static void main(String[] args) {
Hashtable<String,Integer> numbers = new Hashtable<String,Integer>();
numbers.put("one", new Integer(1));
numbers.put("two", new Integer(2));
numbers.put("three", new Integer(3));
String key="three";
Integer n = numbers.get(key);
if (n != null) {
System.out.println(key+" = " + n);
}
}
}

Paulo117
André Castro CE-703 / ITA
Resultado
>three = 3

Paulo118
André Castro CE-703 / ITA
Classes Wrapper
Todo tipo primitivo em Java, tem uma classe
correspondente que pode encapsula-lo

119
Uso de Classes Wrapper
Define constantes úteis, por exemplo:

Conversão entre tipos de dados


Utilize parseXXX para fazer conversões:

120
Outras conversões...

Paulo121
André Castro CE-703 / ITA
Resumindo...
Laços de repetição, comandos condicionais e o acesso a
arrays é feito em Java da mesma forma que em C++
String é uma classe em Java, não um array de caracteres
Nunca compare Strings usando ==
O tratamento de erros é feito através de exceções
(blocos try-catch-finally)
Vector, ArrayList e HashMap são estruturas de dados
muito úteis disponíveis em Java
Podem manter um número arbitrário de elementos

Paulo122
André Castro CE-703 / ITA
Mais sobre modificadores
(métodos e variáveis)
public: o método ou variável ao qual se refere é acessível
de “qualquer lugar” no código
Uma classe deve ser declarada public para ser acessível por
outras classes
Uma classe pública deve estar declarada num arquivo com o
mesmo nome da classe. Ex. “ public class Ship ...” deve estar no
arquivo Ship.java
private: O método ou variável ao qual se refere é
acessível exclusivamente por métodos da mesma classe
Declarar uma variável private a faz acessível pelo resto do código
apenas através de métodos públicos

Paulo123
André Castro CE-703 / ITA
Mais sobre modificadores
(métodos e variáveis)
protected: Acessível apenas a variáveis e métodos da
classe, das classes filhas (herdadas) e das classes que
pertencem ao mesmo pacote
Variáveis e métodos protected são herdados mesmo por classes
que não pertencem ao mesmo pacote
[default]: Similar ao protected, exceto por:
Variáveis e métodos [default] NÃO são herdados por classes que
não pertencem ao mesmo pacote
Em outras palavras: Variáveis e métodos [default] são herdadas
APENAS por classes que pertencem ao mesmo pacote

Paulo124
André Castro CE-703 / ITA
Exemplo - protected

• Cake, ChocolateCake e Pie herdam o campo calories


•Entretanto, se o código na classe Cake tem uma referência ao objeto Pie, o
campo calories de Pie não pode ser acessado em Cake.
•Campos protected de uma classe não podem ser acessados fora de um
mesmo pacote, exceto se na mesma árvore de hierarquia

Paulo125
André Castro CE-703 / ITA
Exemplo – [default]

Paulo126
André Castro CE-703 / ITA
Sumário de modificadores de acesso

Paulo127
André Castro CE-703 / ITA
Outros modificadores

Paulo128
André Castro CE-703 / ITA
Algumas Diretrizes para gerar
bom código
Uma classe deve o menor número possível de métodos
públicos (mas deve ter pelo menos um!)
Isto diminui o acoplamento entre as classes do projeto, o que
facilita a manutenção
Deve-se evitar variáveis públicas. Crie métodos de acesso
get/set. Exemplo:
Class Ship {
private double speed;
public double getSpeed() { return speed; }
public void setSpeed(double speed) {
this.speed=speed;}
}

Paulo129
André Castro CE-703 / ITA
Formatando
Números
Texto
Use DecimalFormat para formatação
Nas versões mais novas, Java implementa um método printf,
semelhante ao C/C++
Abordagem DecimalFormat
1. Crie um objeto DecimalFormat descrevendo a formatação
DecimalFormat formatter= new DecimalFormat(“#,###.##”);
2. Utilize o método de instância format para convertar valores
em string formatadas
formatter.format(24.99);

130
Formatando Números

Paulo131
André Castro CE-703 / ITA
Exemplo – Formatação de Números

Paulo132
André Castro CE-703 / ITA
Resultado – Formatando Números

Paulo133
André Castro CE-703 / ITA
Trabalhando com Datas
Classe Date
Vários métodos deprecated!

Classe Calendar
Uso: Calendar cal=Calendar.getInstance();
cal.setTime(new Date());
Date hoje=cal.getTime();
cal.setTime(int year,int month,int day, int hour,int minute,int second);
cal.set(Calendar.MONTH,Calendar.SEPTEMBER);

Paulo134
André Castro CE-703 / ITA
Formatando datas
/** @param Data a ser formatada
@return Data formatada em texto DD/MM/YY
*/
public static String FormatDate_UK(Date d) {
return
DateFormat.getDateInstance(DateFormat.SHORT,
Locale.UK).format(d);
}
/** @param Data a ser formatada
@return Data formatada em texto MM/DD/YY
*/
public static String FormatDate_USA(Date d) {
return
DateFormat.getDateInstance(DateFormat.SHORT,
Locale.US).format(d);
}

Paulo135
André Castro CE-703 / ITA
Formatando datas
/** @param Data a ser formatada
@return Data formatada em texto corrido na
língua do computador
*/
public static String FormatDate_Default(Date d)
{
return
DateFormat.getDateInstance(DateFormat.LONG,
Locale.getDefault()).format(d);
}
Em computador configurado para português (br):
Retorna: 31 de Outubro de 2006

Paulo136
André Castro CE-703 / ITA
Formatando datas – Abordagem
Direta
public static String FormatDate(Date d) {
if(d==null)
return new String("");
Calendar cal=Calendar.getInstance();
cal.setTime(d);
String year=Integer.toString(cal.get(Calendar.YEAR));
String month=Integer.toString(cal.get(Calendar.MONTH)+1);
String day=Integer.toString(cal.get(Calendar.DAY_OF_MONTH));
String hour=Integer.toString(cal.get(Calendar.HOUR_OF_DAY));
String minute=Integer.toString(cal.get(Calendar.MINUTE));
String second=Integer.toString(cal.get(Calendar.SECOND));
if(month.length()<2)
month="0"+month;
if(day.length()<2)
day="0"+day;
if(hour.length()<2)
hour="0"+hour;
if(minute.length()<2)
minute="0"+minute;
if(second.length()<2)
second="0"+second;

return day+"/"+month+"/"+year+" "+hour+":"+minute+":"+second;

Paulo137
André Castro CE-703 / ITA
Criando datas
public static Date getDate
(int year,int month,int day) {
Calendar cal=Calendar.getInstance();
cal.set(year,month,day,0,0,0);
return cal.getTime();
}

Paulo138
André Castro CE-703 / ITA
Programa de Testes de Data

public class DataTest {


/* funções de manipulação de datas....
......... */

public static void main(String[] args) {


Date hoje=new Date();

System.out.println("FormatDate_UK:
"+DatasTest.FormatDate_UK(hoje));
System.out.println("FormatDate_USA:
"+DatasTest.FormatDate_USA(hoje));
System.out.println("FormatDate_Default:
"+DatasTest.FormatDate_Default(hoje));
Date outroDia=getDate(2007,4,16); // mes inicia em zero
System.out.println("FormatDate_Default:
"+DatasTest.FormatDate_Default(outroDia));

}
}

Paulo139
André Castro CE-703 / ITA
Resultado
FormatDate_UK: 16/04/07
FormatDate_USA: 4/16/07
FormatDate_Default: 16 de Abril de 2007
FormatDate_Default: 16 de Maio de 2007

Paulo140
André Castro CE-703 / ITA
Calendar
Adiantando ou atrasando datas
cal.add(10,Calendar.MONTH)
cal.add(-15,Calendar.YEAR)
Pode-se utilizar GregorianCalendar (subclasse de Calendar)
para adiantar ou movimentar datas
GregorianCalendar gcal=new GregorianCalendar();
Acessando campos de uma data
cal.get(Calendar.MONTH) //retorna inteiro
cal.get(Calendar.SECONDS)

Paulo141
André Castro CE-703 / ITA
Sumário de Hoje
Introdução ao Ambiente Eclipse
Criando workspaces e projetos
Compilando e executando programas
Desenvolvimento de Programas básicos (modo texto)
Primeiros Programas
Javadoc, Os conceitos de CLASSPATH, package e import
Formatando texto

O sistema de I/O Orientado a Objetos do Java


Acessando arquivos Texto
Acessando arquivos Binários
Serialização e armazenamento de Objetos

Paulo142
André Castro CE-703 / ITA
O sistema de IO em Java
A biblioteca java.io tem mais de 60 classes(stream) de
input/output
Dois grandes grupos
Classes baseadas em tráfego de bytes
DataStreams:
Classes baseados em tráfego de caracteres
Reader e Writer
Em qualquer operação de IO pode ocorrer uma exceção
do tipo IOException

Paulo143
André Castro CE-703 / ITA
A classe File

Paulo144
André Castro CE-703 / ITA
Métodos úteis em File

Paulo145
André Castro CE-703 / ITA
Exemplo de File:
Programa que lista o diretório do usuário

Paulo146
André Castro CE-703 / ITA
Resultado

Paulo147
André Castro CE-703 / ITA
Exercício: Listar o conteúdo de
um diretório
Faça um programa em Java que liste o conteúdo de um
diretório passado na linha de comando ou o diretório
corrente, caso não seja solicitado nenhum
Exemplos de uso:
C:>eclipse\ java ListDir “c:\Arquivos de Programa”
Lista o conteúdo do diretório Arquivos de Programa
C:>eclipse\java ListDir
Lista o conteúdo do diretório eclipse:

Paulo148
André Castro CE-703 / ITA
Solução
import java.io.*;

public class DirListing {


public static void main(String []args) {

if(args.length<1) {
args=new String[2];
args[0]=System.getProperty("user.dir");
}
File dir = new File(args[0]);
if(dir.isDirectory()) {
String []list= dir.list();
for(int i=0;i<list.length;i++)
System.out.println("\t"+list[i]);
}
else
System.out.println(args[0]+" não é um diretorio");

}
}149
Paulo André Castro CE-703 / ITA
Resultado

Paulo150
André Castro CE-703 / ITA
Classes para escrever Texto

Paulo151
André Castro CE-703 / ITA
Classes para escrever Texto

Paulo152
André Castro CE-703 / ITA
Exemplo de Escrita de Arquivo de
Texto

Paulo153
André Castro CE-703 / ITA
Codificação de caracteres

Paulo154
André Castro CE-703 / ITA
Classes de Leitura de Streams de
Texto

Paulo155
André Castro CE-703 / ITA
UCS Transformation Format – UTF 8

Paulo156
André Castro CE-703 / ITA
Exemplo - FileReader

Paulo157
André Castro CE-703 / ITA
Resultado - FileReader

Paulo158
André Castro CE-703 / ITA
I/O em Arquivos (Streams) Binários

Paulo159
André Castro CE-703 / ITA
Classes para Escrita em Streams
Binárias

Paulo160
André Castro CE-703 / ITA
Classes para Escrita em Streams
Binárias

Paulo161
André Castro CE-703 / ITA
Exemplo – Escrita em Arquivos
Binários

Paulo162
André Castro CE-703 / ITA
Classes para Leitura em Streams
Binárias

Paulo163
André Castro CE-703 / ITA
Classes para Leitura em Streams
Binárias

Paulo164
André Castro CE-703 / ITA
Exemplo – Leitura de Arquivos
Binários

Paulo165
André Castro CE-703 / ITA
Resumo
Um objeto File pode referir-se tanto a um arquivo quanto a um
diretório
Use classes Reader/Writer para lidar com streams baseadas em
caracteres
Para ler linhas use BufferedReader
Use classes de formatação para a formatação de texto (Ex.
DecimalFormat, package java.text)
Use classes DataStream para lidar com streams baseadas em bytes.
Associe um FileOutputStream a um DataOutputSteam para escrever
em arquivos binários tipos básicos do Java
Associe um FileInputStream a um DataInputStream para ler de arquivos
binários usando tipos básicos do Java
Para ler ou escrever objetos em streams deve-se fazer uso das classes
ObjectOutputStream e ObjectInputStream.

Paulo166
André Castro CE-703 / ITA
Introdução a Ambientes de
Desenvolvimento Integrado
Sumário de Hoje
Introdução ao Ambiente Eclipse
Criando workspaces e projetos
Compilando e executando programas
Desenvolvimento de Programas básicos (modo texto)
Os conceitos de CLASSPATH, package e import
Formatando texto

O sistema de I/O Orientado a Objetos do Java


Acessando arquivos Texto
Acessando arquivos Binários
Serialização e armazenamento de Objetos
Projetando Programas Orientados a Objetos

Paulo168
André Castro CE-703 / ITA
Eclipse IDE

Paulo169
André Castro CE-703 / ITA
Criando Workspace

Paulo170
André Castro CE-703 / ITA
Criando projetos
Menu File | New | Project
Java Project
A partir de código pré-
existente arquivos ant
CVS
Java
Java Project
Java Project from ..Ant
Plug-In Development

171
Criando Projetos – Passo 2
Escolha
Nome do Projeto
Projeto vazio ou criado a
partir de código pré-
existente
JDK alvo
Project Layout

172
Configuração do Projeto
Escolha dos diretórios
com código-fonte
Bibliotecas utilizadas
Projetos requeridos
Ordem de
importação/exportação

173
Opções de Projeto
Criação de
elementos do Projeto
Classes, interfaces, etc.
Refactoring
Propriedades,etc.

174
Propriedades do Projeto
Configuração do
Classpath e acesso a
bibliotecas
Configuração de
diretórios de destino e
fonte
Configuração de destino
do Javadoc
Referências a outros
projetos, etc.

175
Alguns Exemplos de Programas

Paulo176
André Castro CE-703 / ITA
Alguns Exemplos de Programa
Exemplo 1:
public class Hello {
public static void main(String args[])
{ System.out.println(“Hello World!”);
}
}
Compile e Execute o programa acima através do Eclipse

Paulo177
André Castro CE-703 / ITA
Exemplo 2

Compile e Execute o programa acima

Paulo178
André Castro CE-703 / ITA
Inserindo argumentos para os
programas através do Eclipse

• Menu Run | Run ...


•Tab Arguments

Paulo179
André Castro CE-703 / ITA
Exemplo 3 – Usando Loops

Paulo180
André Castro CE-703 / ITA
Exemplo 4 – Loops Aninhados

Paulo181
André Castro CE-703 / ITA
Exemplo 5

Paulo182
André Castro CE-703 / ITA
Exemplo 5

Paulo183
André Castro CE-703 / ITA
Saída do Exemplo 5

Paulo184
André Castro CE-703 / ITA
Onde estão as classes ? CLASSPATH

Paulo185
André Castro CE-703 / ITA
Pacotes...

Paulo186
André Castro CE-703 / ITA
Pacotes...

Paulo187
André Castro CE-703 / ITA
Exercício
Criar packages hello, triangle, showArgs e ship
Mover programas correspondentes
Definir variáveis de instância de Ship como private e criar
métodos de acesso

Paulo188
André Castro CE-703 / ITA
Exercício 1
Crie um programa que armazene uma lista de
Funcionários (name,salary,hireDay) criados
“manualmente” em um arquivo texto
Leia este arquivo texto, atualizando a lista em memória e
Liste na tela os dados dos funcionários lidos
Use no mínimo duas classes: DataFileTest e Employee
Formato do registro:
[name] | [salary] | [year] | [month] | [day]
Utilizar StringTokenizer para separar campos
StringTokenizer t=new StringTokenizer(str,”|”);
String s=t.nextToken();

Paulo189
André Castro CE-703 / ITA
Exercício 1.1
Crie um método em Employee que incrementa o salário
de um funcionario pelo percentual passado como
parâmetro. Após a leitura dos dados do arquivo aumente
o salário de todos em 10%. Apresente os dados

Paulo190
André Castro CE-703 / ITA
Solução – Exercício 1 – Classe
DataFileTest
public static void main(String[] args)
public class DataFileTest { Employee[] staff = new Employee[3];
{ static void writeData(Employee[] e, PrintWriter os) staff[0] = new Employee("Harry Hacker", 35500,
Format.getDate(1989,10,1));
throws IOException
staff[1] = new Employee("Carl Cracker", 75000,
{ os.println(e.length);
Format.getDate(1987,12,15));
staff[2] = new Employee("Tony Tester", 38000,
int i; Format.getDate(1990,3,15));
for (i = 0; i < e.length; i++) try
e[i].writeData(os); { PrintWriter os = new PrintWriter(new
} FileWriter("employee.dat"));
writeData(staff, os); os.close();
} catch(IOException e)
static Employee[] readData(BufferedReader is)
{ System.out.print("Error: " + e);
throws IOException
System.exit(1); }
{ int n = Integer.parseInt(is.readLine()); try
Employee[] e = new Employee[n]; { BufferedReader is = new BufferedReader(new
int i; FileReader("employee.dat"));
for (i = 0; i < n; i++) Employee[] in = readData(is);
{ e[i] = new Employee(); for (i = 0; i < in.length; i++) in[i].print();
e[i].readData(is); is.close();
} catch(IOException e)
}
{ System.out.print("Error: " + e); System.exit(1); } }}
return e;
}
Paulo191
André Castro CE-703 / ITA
class Employee public void writeData(PrintWriter os) throws IOException
{ os.print(name+ "|");
{ public Employee(String n, double s, Date d)
os.print( salary+ "|");
{ name = n;
os.print(Format.getYear(hireDay)+ "|");
salary = s; os.print(Format.getMonth(hireDay)+ "|");
hireDay = d; os.print(Format.getDayofMonth(hireDay)+ "\n");
} }
public Employee() {}
public void print() public void readData(BufferedReader is) throws IOException
{ System.out.println(name + " " + salary { String s = is.readLine();
StringTokenizer t = new StringTokenizer(s, "|");
+ " " + hireYear());
name = t.nextToken();
}
salary = Double.parseDouble(t.nextToken());
public void raiseSalary(double byPercent) int y = Integer.parseInt(t.nextToken());
{ salary *= 1 + byPercent / 100; int m = Integer.parseInt(t.nextToken());
} int d = Integer.parseInt(t.nextToken());
public int hireYear() hireDay = Format.getDate(y,m,d);
{ return Format.getYear(hireDay); }
}
private String name;
private double salary;
private Date hireDay;
}

Paulo192
André Castro CE-703 / ITA
Solução 1.1
Na classe DataFileTest
public void raiseSalary(Employee[] e) {
int i;
for (i = 0; i < staff.length; i++)
staff[i].raiseSalary(10.0);
}
Na classe Employee,
public void raiseSalary(double byPercent)
{ salary *= 1 + byPercent / 100;
}

Paulo193
André Castro CE-703 / ITA
Exercício 2 – Opcional/Homework
Refaça o exercício 1, agora acessando arquivos binários
através da classe RandomAccessFile:
Crie um programa que armazene uma lista de
Funcionários (name,salary,hireDay) criados
“manualmente” e grave estes objetos em um arquivo Leia
o arquivo de dados, atualizando a lista em memória e
Liste na tela os dados dos funcionários lidos
Use no mínimo duas classes: ObjectFileTest e Employee

Paulo194
André Castro CE-703 / ITA
Multitarefa
Multithreading
Sumário
5.2.1 Introdução
5.2.2 Estados de um Thread: Ciclo de vida de um Thread
5.2..3 Prioridades de Thread Priorities and Thread Scheduling
5.2.4 Creating and Executing Threads
5.2.5 Thread Synchronization
5.2.6 Producer/Consumer Relationship without Synchronization
5.2.7 Producer/Consumer Relationship with Synchronization
5.2.8 Daemon Threads
5.2.9 Runnable Interface

Paulo André Castro CE-703 / ITA


5.2.1 Introdução
Java provê multithreading em sua biblioteca padrão
Multithreading melhora a performance de alguns programas
Permite que um programa continue respondendo a pedidos do
usuário, enquanto faz atividades demoradas

Paulo André Castro CE-703 / ITA


Estados de um Thread: Ciclo de vida de
um Thread
Estados de Thread
Born state
Quando acabou de ser criado
Ready state
Método start de Thread é chamado
Thread está pronto para ser executado
Running state
Thread é alocado a um processador para execução
Dead state
Thread completou sua tarefa (run)
Waiting State
Espera até ser notificado
Sleeping State
Espera um tempo pré-determinado
Blocked State
Espera até que um determinado recurso I/O ou código sincronizado seja
liberado

Paulo André Castro CE-703 / ITA


Fig. 5.2.1 Thread life-cycle statechart
diagram
Born

start

Ready

thread dispatch
quantum expiration (assign a
timeout expires yield processor)

I/O completes
acquire lock
interrupt
interrupt
notifyAll
notify

Running

Waiting Sleeping Blocked

sleep interval When a thread completes


expires (returns from its run method),
interrupt it reaches the Dead state
(shown here as the final state)

Paulo André Castro CE-703 / ITA


5.2.3 Thread Priorities and Thread
Scheduling
Java thread priority
Priority in range 1-10
Timeslicing
Each thread assigned time on the processor (called a quantum)
Keeps highest priority threads running

Paulo André Castro CE-703 / ITA


Fig. 5.2.2 Thread priority scheduling
example
Ready threads

Thread.MAX_PRIORITY Priority 10 A B

Priority 9 C

Priority 8

Priority 7 D E F

Priority 6 G

Thread.NORM_PRIORITY Priority 5 H I

Priority 4

Priority 3

Priority 2 J K

Thread.MIN_PRIORITY Priority 1

Paulo André Castro CE-703 / ITA


5.2.4 Creating and Executing Threads
Sleep state
Thread method sleep called
Thread sleeps for a set time interval then awakens

Paulo André Castro CE-703 / ITA


1 // Fig. 5.2.3: ThreadTester.java
2 // Multiple threads printing at different intervals.
3
4 public class ThreadTester {
5
6 public static void main( String [] args )
7 {
8 // create and name each thread create four
9 PrintThread thread1 = new PrintThread( "thread1" ); PrintThreads
10 PrintThread thread2 = new PrintThread( "thread2" );
11 PrintThread thread3 = new PrintThread( "thread3" );
12
13 System.err.println( "Starting threads" );
14 call start methods
15 thread1.start(); // start thread1 and place it in ready state
16 thread2.start(); // start thread2 and place it in ready state
17 thread3.start(); // start thread3 and place it in ready state
18
19 System.err.println( "Threads started, main ends\
ends\n" );
20
21 } // end main
22
23 } // end class ThreadTester
24
25 // class PrintThread controls thread execution
26 class PrintThread extends Thread {
27 private int sleepTime;
28
PrintThread extends
29 // assign name to thread by calling superclass constructor
Thread
30 public PrintThread( String name )
31 {
32 super(
super( name );
33
34 // pick random sleep time between 0 and 5 seconds Constructor initializes
35 sleepTime = ( int ) ( Math.random() * 5001 ); sleepTime
36 }
37
When the thread
38 // method run is the code to be executed by new thread
enters the running
39 public void run()
state, run is called
40 {
41 // put thread to sleep for sleepTime amount of time
42 try {
43 System.err.println(
44 getName() + " going to sleep for " + sleepTime );
45
46 Thread.sleep( sleepTime );
47 }
48
49 // if thread interrupted during sleep, print stack trace
50 catch ( InterruptedException exception ) {
51 exception.printStackTrace();
52 }
53
54 // print thread name
55 System.err.println( getName() + " done sleeping" );
56
57 } // end method run
58
59 } // end class PrintThread

Starting threads
Threads started, main ends

thread1 going to sleep for 1217


thread2 going to sleep for 3989
thread3 going to sleep for 662
thread3 done sleeping
thread1 done sleeping
thread2 done sleeping
Starting threads
thread1 going to sleep for 314
thread2 going to sleep for 1990
Threads started, main ends

thread3 going to sleep for 3016


thread1 done sleeping
thread2 done sleeping
thread3 done sleeping
5.2.5 Thread Synchronization
Java uses monitors for thread synchronization
The sychronized keyword
Every synchronized method of an object has a monitor
One thread inside a synchronized method at a time
All other threads block until method finishes
Next highest priority thread runs when method finishes

Paulo André Castro CE-703 / ITA


5.2.6 Producer/Consumer Relationship
without Synchronization
Buffer
Shared memory region
Producer thread
Generates data to add to buffer
Calls wait if consumer has not read previous message in
buffer
Writes to empty buffer and calls notify for consumer
Consumer thread
Reads data from buffer
Calls wait if buffer empty
Synchronize threads to avoid corrupted data

Paulo André Castro CE-703 / ITA


Exemplo de Saída: SharedBuffer
Consumer reads -1
Producer writes 1
Consumer reads 1
Consumer reads 1
Consumer reads 1
Consumer read values totaling: 2.
Terminating Consumer.
Producer writes 2
Producer writes 3
Producer writes 4
Producer done producing.
Terminating Producer.

Producer writes 1
Producer writes 2
Consumer reads 2
Producer writes 3
Consumer reads 3
Producer writes 4
Producer done producing.
Terminating Producer.
Consumer reads 4
Consumer reads 4
Consumer read values totaling: 13.
Terminating Consumer.
Producer writes 1
Consumer reads 1
Producer writes 2
Consumer reads 2
Producer writes 3
Consumer reads 3
Producer writes 4
Producer done producing.
Terminating Producer.
Consumer reads 4
Consumer read values totaling: 10.
Terminating Consumer.
1 // Buffer.java
2 // Buffer interface specifies methods called by Producer and Consumer.
3
4 public interface Buffer {
5 public void set( int value ); // place value into Buffer
6 public int get(); // return value from Buffer
7 }
1 // Fig. 5.2.5: Producer.java
2 // Producer's run method controls a thread that
3 // stores values from 1 to 4 in sharedLocation.
4
Producer extends
5 public class Producer extends Thread {
Thread
6 private Buffer sharedLocation; // reference to shared object
7 This is a shared object
8 // constructor
9 public Producer( Buffer shared )
10 {
11 super(
super( "Producer" );
12 sharedLocation = shared;
13 }
Method run is overridden
14
15 // store values from 1 to 4 in sharedLocation
16 public void run()
17 {
18 for ( int count = 1; count <= 4; count++ ) {
The thread goes to sleep,
19 int sum=0;
then the buffer is set
20 // sleep 0 to 3 seconds, then place value in Buffer
21 try {
22 Thread.sleep( ( int ) ( Math.random() * 3001 ) ); sum+=count;
23 sharedLocation.set( count );
24 }
25
26 // if sleeping thread interrupted, print stack trace
27 catch ( InterruptedException exception ) {
28 exception.printStackTrace();
29 }
30
31 } // end for
32
33 System.err.println( getName() + " done producing totaling “+sum +
34 "\nTerminating " + getName() + ".");
".");
35
36 } // end method run
37
38 } // end class Producer
1 // Fig. 5.2.6: Consumer.java
2 // Consumer's run method controls a thread that loops four
3 // times and reads a value from sharedLocation each time.
4
Consumer extends
5 public class Consumer extends Thread {
Thread
6 private Buffer sharedLocation; // reference to shared object
7 This is a shared object
8 // constructor
9 public Consumer( Buffer shared )
10 {
11 super(
super( "Consumer" );
12 sharedLocation = shared;
13 }
Method run is overridden
14
15 // read sharedLocation's value four times and sum the values
16 public void run()
17 {
18 int sum = 0;
19
20 for ( int count = 1; count <= 4; count++ ) { The thread goes to sleep,
21 then the buffer is read
22 // sleep 0 to 3 seconds, read value from Buffer and add to sum
23 try {
24 Thread.sleep( ( int ) ( Math.random() * 3001 ) );
25 sum += sharedLocation.get();
26 }
27
28 // if sleeping thread interrupted, print stack trace
29 catch ( InterruptedException exception ) {
30 exception.printStackTrace();
31 }
32 }
33
34 System.err.println( getName() + " read values totaling: " + sum +
35 ".\
".\nTerminating " + getName() + ".");
".");
36
37 } // end method run
38
39 } // end class Consumer
1 // UnsynchronizedBuffer.java
2 // UnsynchronizedBuffer represents a single shared integer.
3 This class implements the
4 public class UnsynchronizedBuffer implements Buffer { Buffer interface
5 private int buffer = -1; // shared by producer and consumer threads
6 The data is a single integer
7 // place value into buffer
8 public void set( int value )
This method sets the value
9 {
in the buffer
10 System.err.println( Thread.currentThread().getName() +
11 " writes " + value );
12
13 buffer = value;
14 }
15
16 // return value from buffer This method reads the
17 public int get() value in the buffer
18 {
19 System.err.println( Thread.currentThread().getName() +
20 " reads " + buffer );
21
22 return buffer;
23 }
24
25 } // end class UnsynchronizedBuffer
1 // SharedBufferTest.java
2 // SharedBufferTest creates producer and consumer threads.
3
4 public class SharedBufferTest {
5
6 public static void main( String [] args )
7 {
Create a Buffer object
8 // create shared object used by threads
9 Buffer sharedLocation = new UnsynchronizedBuffer();
10 Create a Producer and a
11 // create producer and consumer objects Consumer
12 Producer producer = new Producer( sharedLocation );
13 Consumer consumer = new Consumer( sharedLocation ); Start the Producer and
14 Consumer threads
15 producer.start(); // start producer thread
16 consumer.start(); // start consumer thread
17
18 } // end main
19
20 } // end class SharedCell
5.2.7 Producer/Consumer Relationship
with Synchronization
Synchronize threads to ensure correct data
Exemplo Sincronizado: SynchronizedBuffer

Paulo André Castro CE-703 / ITA


1 // Fig. 5.2.9: SynchronizedBuffer.java
This class implements the
2 // SynchronizedBuffer synchronizes access to a single shared integer.
Buffer interface
3
4 public class SynchronizedBuffer implements Buffer {
5 Remember
private int buffer = -1; // shared by producer and consumer threads the number of
6 private int occupiedBufferCount = 0; // count of occupied buffersfilled spaces
7
Method set is declared
8 // place value into buffer
synchronized
9 public synchronized void set( int value )
10 {
Get the name of the thread
11 // for output purposes, get name of thread that called this method
12 String name = Thread.currentThread().getName();
13
14 // while there are no empty locations, place thread in waiting state
15 while ( occupiedBufferCount == 1 ) { Wait while the buffer is filled
16
17 // output thread information and buffer information, then wait
18 try {
19 System.err.println( name + " tries to write." );
20 displayState( "Buffer full. " + name + " waits." );
21 wait();
22 }
23
24 // if waiting thread interrupted, print stack trace
25 catch ( InterruptedException exception ) {
26 exception.printStackTrace();
27 }
28
29 } // end while
30
Write to the buffer
31 buffer = value; // set new buffer value
32
33 // indicate producer cannot store another value
34 // until consumer retrieves current buffer value Increment the buffer count
35 ++occupiedBufferCount;
36
37 displayState( name + " writes " + buffer ); Alert a waiting thread
38
39 notify(); // tell waiting thread to enter ready state
40
41 } // end method set; releases lock on SynchronizedBuffer
Method get is declared
42 synchronized
43 // return value from buffer
44 public synchronized int get()
Get the name of the thread
45 {
46 // for output purposes, get name of thread that called this method
47 String name = Thread.currentThread().getName();
48
49 // while no data to read, place thread in waiting state
50 while ( occupiedBufferCount == 0 ) {
51
52 Wait
// output thread information and buffer information, thenwhile
wait the buffer is empty
53 try {
54 System.err.println( name + " tries to read." );
55 displayState( "Buffer empty. " + name + " waits." );
56 wait();
57 }
58
59 // if waiting thread interrupted, print stack trace
60 catch ( InterruptedException exception ) {
61 exception.printStackTrace();
62 }
63
64 } // end while
65
Decrement the buffer count
66 // indicate that producer can store another value
67 // because consumer just retrieved buffer value
68 --occupiedBufferCount;
--occupiedBufferCount; Alert a waiting thread
69
70 displayState( name + " reads " + buffer );
Return the buffer
71
72 notify(); // tell waiting thread to become ready to execute
73
74 return buffer;
75
76 } // end method get; releases lock on SynchronizedBuffer
77
78 // display current operation and buffer state
79 public void displayState( String operation )
80 {
81 StringBuffer outputLine = new StringBuffer( operation );
82 outputLine.setLength( 40 );
83 outputLine.append( buffer + "\t\t" + occupiedBufferCount );
84 System.err.println( outputLine );
85 System.err.println();
86 }
87
88 } // end class SynchronizedBuffer
1 // SharedBufferTest2.java
2 // SharedBufferTest2creates producer and consumer threads.
3
4 public class SharedBufferTest2 {
5
6 public static void main( String [] args ) Create a Buffer object
7 {
8 // create shared object used by threads; we use a SynchronizedBuffer
9 // reference rather than a Buffer reference so we can invoke
10 // SynchronizedBuffer method displayState from main
11 SynchronizedBuffer sharedLocation = new SynchronizedBuffer();
12
13 // Display column heads for output
14 StringBuffer columnHeads = new StringBuffer( "Operation" );
15 columnHeads.setLength( 40 );
16 columnHeads.append( "Buffer\
"Buffer\t\tOccupied Count" ); Output initial state
17 System.err.println( columnHeads );
18 System.err.println();
Create a Producer and a
19 sharedLocation.displayState( "Initial State" );
Consumer
20
21 // create producer and consumer objects
22 Producer producer = new Producer( sharedLocation );
23 Consumer consumer = new Consumer( sharedLocation );
24
25 producer.start(); // start producer thread
26 consumer.start(); // start consumer thread Start the Producer and
27 Consumer threads
28 } // end main
29
30 } // end class SharedBufferTest2

Operation Buffer Occupied Count


Initial State -1 0
Consumer tries to read.
Buffer empty. Consumer waits. -1 0

Producer writes 1 1 1

Consumer reads 1 1 0

Consumer tries to read.


Buffer empty. Consumer waits. 1 0

Producer writes 2 2 1

Consumer reads 2 2 0

Producer writes 3 3 1
Consumer reads 3 3 0

Consumer tries to read.


Buffer empty. Consumer waits. 3 0

Producer writes 4 4 1

Consumer reads 4 4 0
Producer done producing.
Terminating Producer.

Consumer read values totaling: 10.


Terminating Consumer.
Operation Buffer Occupied Count

Initial State -1 0

Consumer tries to read.


Buffer empty. Consumer waits. -1 0

Producer writes 1 1 1

Consumer reads 1 1 0

Producer writes 2 2 1
Producer tries to write.
Buffer full. Producer waits. 2 1

Consumer reads 2 2 0

Producer writes 3 3 1

Consumer reads 3 3 0

Producer writes 4 4 1

Producer done producing.


Terminating Producer.
Consumer reads 4 4 0

Consumer read values totaling: 10.


Terminating
Operation Consumer. Buffer Occupied Count

Initial State -1 0

Producer writes 1 1 1

Consumer reads 1 1 0

Producer writes 2 2 1
Consumer reads 2 2 0

Producer writes 3 3 1

Consumer reads 3 3 0

Producer writes 4 4 1

Producer done producing.


Terminating Producer.
Consumer reads 4 4 0

Consumer read values totaling: 10.


Terminating Consumer.
5.2.9 Daemon Threads
Run for benefit of other threads
Do not prevent program from terminating
Garbage collector is a daemon thread
Set daemon thread with method setDaemon
setDaemon(true);
setDaemon(false);

Paulo André Castro CE-703 / ITA


5.2.10 Runnable Interface
A class cannot extend more than one class
Implement Runnable for multithreading support
Exemplo: RandomCharacters.java

Paulo André Castro CE-703 / ITA


1 // RandomCharacters.java
2 // Class RandomCharacters demonstrates the Runnable interface
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class RandomCharacters extends JApplet implements ActionListener {
8 private String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
9 private final static int SIZE = 3;
10 private JLabel outputs[];
11 private JCheckBox checkboxes[];
12 private Thread threads[];
13 private boolean suspended[];
14
15 // set up GUI and arrays
16 public void init()
17 {
18 outputs = new JLabel[ SIZE ];
19 checkboxes = new JCheckBox[ SIZE ];
20 threads = new Thread[ SIZE ];
21 suspended = new boolean[
boolean[ SIZE ];
22
23 Container container = getContentPane();
24 container.setLayout( new GridLayout( SIZE,
SIZE, 2, 5, 5 ) );
25
26 // create GUI components, register listeners and attach
27 // components to content pane
28 for ( int count = 0; count < SIZE;
SIZE; count++ ) {
29 outputs[ count ] = new JLabel();
30 outputs[ count ].setBackground( Color.GREEN
Color.GREEN );
31 outputs[ count ].setOpaque( true );
32 container.add( outputs[ count ] );
33
34 checkboxes[ count ] = new JCheckBox( "Suspended" );
35 checkboxes[ count ].addActionListener( this );
Applet start method
36 container.add( checkboxes[ count ] );
37 }
38
39 } // end method init
Create three Thread objects
40
and initialize each with a
41 // create and start threads each time start is called (i.e., after
RunnableObject
42 // init and when user revists Web page containing this applet)
43 public void start()
44 {
45 for ( int count = 0; count < threads.length; count++ ) {
46
47 // create Thread; initialize object that implements Runnable
Call thread start
48 threads[ count ] =
method
49 new Thread( new RunnableObject(), "Thread " + ( count + 1 ) );
50
51 threads[ count ].start(); // begin executing Thread
52 }
53 }
54
55 // determine thread location in threads array
56 private int getIndex( Thread current )
57 {
58 for ( int count = 0; count < threads.length; count++ )
59 if ( current == threads[ count ] )
60 return count;
61
62 return -1;
63 } Method stop stops all
64 threads
65 // called when user switches Web pages; stops all threads
66 public synchronized void stop() Set thread references
67 { in array threads to
68 // set references to null to terminate each thread's run method null
69 for ( int count = 0; count < threads.length; count++ ) Invoke method
70 threads[ count ] = null;
null; notifyAll to ready
71
waiting threads
72 notifyAll(); // notify all waiting threads, so they can terminate
73 }
74
75 // handle button events
76 public synchronized void actionPerformed( ActionEvent event )
77 {
78 for ( int count = 0; count < checkboxes.length; count++ ) {
79
80 if ( event.getSource() == checkboxes[ count ] ) {
81 suspended[ count ] = !suspended[ count ];
82 Toggle boolean
83 // change label color on suspend/resume value in array
84 outputs[ count ].setBackground( suspended
85 suspended[ count ] ? Color.RED
Color.RED : Color.GREEN
Color.GREEN );
86
87 // if thread resumed, make sure it starts executing
88 if ( !suspended[ count ] )
89 notifyAll();
90
91 return;
return;
Call notifyAll to start
92 }
ready threads
93 }
94
95 } // end method actionPerformed
Class RunnableObject
96
implements Runnable
97 // private inner class that implements Runnable to control threads
interface
98 private class RunnableObject implements Runnable {
99
Declare method run
100 // place random characters in GUI, variables currentThread and
101 // index are final so can be used in an anonymous inner class
102 public void run()
103 {
104 // get reference to executing thread
105 final Thread currentThread = Thread.currentThread();
106
107 // determine thread's position in array
108 final int index = getIndex( currentThread );
109 The while loop executes as
110 // loop condition determines when thread should stop; loop long as the index of array
111 // terminates when reference threads[ index ] becomes null threads equals
112 while ( threads[ index ] == currentThread ) { currentThread
113
114 // sleep from 0 to 1 second
115 try {
116 Thread.sleep( ( int ) ( Math.random() * 1000 ) );
117
118 // determine whether thread should suspend execution; The synchronized
119 // synchronize on RandomCharacters applet object block helps suspend
120 synchronized(
synchronized( RandomCharacters.this
RandomCharacters.this ) { currently executing
121 thread
122 while ( suspended[ index ] &&
123 threads[ index ] == currentThread ) {
Invoke method wait
124
on applet to place
125 // temporarily suspend thread execution
thread in waiting
126 RandomCharacters.this
RandomCharacters.this.wait();
this.wait();
state
127 }
128 } // end synchronized statement
129
130 } // end try
131
132 // if thread interrupted during wait/sleep, print stack trace
133 catch ( InterruptedException exception ) {
134 exception.printStackTrace();
135 }
136
137 // display character on corresponding JLabel
138 SwingUtilities.invokeLater( Anonymous inner
139 new Runnable() { class implements
140 Runnable interface
141 // pick random character and display it
142 public void run()
143 {
144 char displayChar =
145 alphabet.charAt( ( int ) ( Math.random() * 26 ) );
146
147 outputs[ index ].setText(
148 currentThread.getName() + ": " + displayChar );
149 }
150
151 } // end inner class
152
153 ); // end call to SwingUtilities.invokeLater

Você também pode gostar