Post on 25-Mar-2020
1
CE-703Programação Orientada a Objetos paraSistemas Embutidos
Prof. Paulo André Castro pauloac@ita.brwww.comp.ita.br/~pauloac Sala 110, IEC-ITA
CE-703 / ITAPaulo André Castro
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)
CE-703 / ITAPaulo André Castro
Camadas de um Sistema Completo
CE-703 / ITAPaulo André Castro
Arquitetura de Software Típica em Dispositivos Móveis
CE-703 / ITAPaulo André Castro
Processo de Desenvolvimento de Software Embutido
CE-703 / ITAPaulo André Castro
Java para Sistemas Embutidos
2
CE-703 / ITAPaulo André Castro CE-703 / ITAPaulo André Castro8
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
CE-703 / ITAPaulo André Castro9
Programação Estrurada
dadosglobais
Proc2dadoslocais
internos ou
externos
dadosglobais
����Principal
acessa
ProcProc
Procdados
invoca
CE-703 / ITAPaulo André Castro10
Programação Orientada a Objetos
invoca
classe
classe
classe------------------------------
dados
dados
dados
Classes contémprocedimentos
(métodos)
Dados de cada classe/
objeto
relacionamento
acessa
CE-703 / ITAPaulo André Castro11
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
CE-703 / ITAPaulo André Castro12
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)
3
CE-703 / ITAPaulo André Castro13
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
CE-703 / ITAPaulo André Castro14
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
int dia,mes,ano
alteraData()
públicos/privativos
CE-703 / ITAPaulo André Castro15
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
CE-703 / ITAPaulo André Castro16
UML: notações de classesNome
Atributos
Operações
Nome
Atributos
Operações
itálico: abstrataoperações não implementadas
Nome
String
Date
CE-703 / ITAPaulo André Castro17
Exemplo em UML - Herança
CE-703 / ITAPaulo André Castro 18
Exemplo em UML – Está correto ?
4
CE-703 / ITAPaulo André Castro
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; }
}
}..........................................................
CE-703 / ITAPaulo André Castro
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;
} }
CE-703 / ITAPaulo André Castro21
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
CE-703 / ITAPaulo André Castro22
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
CE-703 / ITAPaulo André Castro23
Exemplo de Herança Múltipla
CE-703 / ITAPaulo André Castro24
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
5
CE-703 / ITAPaulo André Castro25
Agregação em UML
CE-703 / ITAPaulo André Castro26
Composição: Tipo especial de AgregaçãoParte pertence a apenas um todo e tem tempo de vida igual ao todo
CE-703 / ITAPaulo André Castro27
Outras Relações: Associação
CE-703 / ITAPaulo André Castro28
Outras Relações: Associação com Qualificação
CE-703 / ITAPaulo André Castro29
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
CE-703 / ITAPaulo André Castro30
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.
6
CE-703 / ITAPaulo André Castro31
Polimorfismo
� Um mesmo comando enviado para objetos diferentes gera (ou pode gerar) ações diferentes.
� Exemplo:� Comando: Mover
� Carro
� Avião
� Pessoa
CE-703 / ITAPaulo André Castro32
Exemplo de Orientação a Objetos – classe PessoaArquivo: 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; }}}
CE-703 / ITAPaulo André Castro33
Exemplo de Orientação a Objetos – subclasse CasadoArquivo: Casado.java
public class Casado extends Pessoa {public boolean ehResponsavel() {
return true;}
public Casado(String nome,int id,boolean sexo) { super(nome,idade,sexo);
} }
CE-703 / ITAPaulo André Castro
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?
CE-703 / ITAPaulo André Castro35
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);
} }
CE-703 / ITAPaulo André Castro36
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));}
}
7
CE-703 / ITAPaulo André Castro37
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
CE-703 / ITAPaulo André Castro
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
CE-703 / ITAPaulo André Castro39
Exemplo - Java
class Pessoa{public String nome;public char sexo;public Data dataNasc;
----}
public class Ator extends Pessoa{public String contrato;/* campos herdadospublic String nome;public char sexo;public Date dataNasc; */
-----}
public class Aluno extends Pessoa{public long matric;/* campos herdados public String nome;public char sexo;public Data dataNasc; */
-----}
CE-703 / ITAPaulo André Castro40
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;
}
CE-703 / ITAPaulo André Castro41
Herança e Interfaces
� Uma classe em Java pode implementar várias interfaces
public class Class1 extends Class2 implements
Interface1,Interface2,Interface3 {
......
....
}
CE-703 / ITAPaulo André Castro42
Outras Relações: Realização
8
CE-703 / ITAPaulo André Castro43
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)
CE-703 / ITAPaulo André Castro44
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
CE-703 / ITAPaulo André Castro45
Java x C++
CE-703 / ITAPaulo André Castro46
Criando Programas java
CE-703 / ITAPaulo André Castro47
Exemplo
CE-703 / ITAPaulo André Castro
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; }}..........................................................
9
CE-703 / ITAPaulo André Castro49
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 Classespublic class MyClasse {......}
� Criando Objetos a partir de Classes� Uso do “new”
CE-703 / ITAPaulo André Castro
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.
CE-703 / ITAPaulo André Castro51
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 = ?
CE-703 / ITAPaulo André Castro52
Formato de uma Definição de Classe em Java
CE-703 / ITAPaulo André Castro53
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
CE-703 / ITAPaulo André Castro54
Exemplo – Orientado a Objetos?
10
CE-703 / ITAPaulo André Castro55
Exemplos
CE-703 / ITAPaulo André Castro56
Resultado
CE-703 / ITAPaulo André Castro57
Problemas na Modelagem?
� Código específico a uma classe está escrito apenas nesta classe?
CE-703 / ITAPaulo André Castro58
Métodos: Exemplo
CE-703 / ITAPaulo André Castro59
Exemplo (cont.)
CE-703 / ITAPaulo André Castro60
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()
11
CE-703 / ITAPaulo André Castro61
Métodos Especiais: Construtores (2)
CE-703 / ITAPaulo André Castro62
Métodos Especiais: Construtores (3)
CE-703 / ITAPaulo André Castro63
Métodos Especiais: Construtores (4)
CE-703 / ITAPaulo André Castro64
A variável especial: this
CE-703 / ITAPaulo André Castro65
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();
CE-703 / ITAPaulo André Castro66
Convenções e Boas Práticas em OOResumo
� 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
12
CE-703 / ITAPaulo André Castro67
Convenções e Boas Práticas em OOResumo� 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
CE-703 / ITAPaulo André Castro68
Convenções e características em JavaResumo
� 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
CE-703 / ITAPaulo André Castro69
Fundamentos de Programação Java
� Comandos
� Sintaxe
� Estrutura
� Exemplos
CE-703 / ITAPaulo André Castro
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>;
CE-703 / ITAPaulo André Castro
Tipos básicos de Variáveis
T ipo T am anho
byte 1 bytes
short 2 bytes
in t 4 bytes
long 8 bytes
float 4 bytes
doub le 8 bytes
char 2 bytes
boo lean 1 b it
CE-703 / ITAPaulo André Castro
Variáveis
� Declaração � int inteiro; char letra;
� byte apenasUmByte;
� Declaração e Inicialização� float saldoConta=0.0;
� boolean serOuNaoSer=false;
13
CE-703 / ITAPaulo André Castro
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);
CE-703 / ITAPaulo André Castro74
Tipos Complexos
CE-703 / ITAPaulo André Castro75
Exemplo
CE-703 / ITAPaulo André Castro76
Exemplo
CE-703 / ITAPaulo André Castro77
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 }
CE-703 / ITAPaulo André Castro78
Comandos...
� Comando_condicional := if ( Expressão ) Comando_1| if ( Expressão ) Comando_1 else Comando_2
� Comando_iterativo := Comando_while | Comando_do | Comando_for
14
CE-703 / ITAPaulo André Castro79
Comando de Seleção em Javaswitch ( 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;
}
CE-703 / ITAPaulo André Castro80
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.
CE-703 / ITAPaulo André Castro81
Comandos de repetição
CE-703 / ITAPaulo André Castro82
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.
CE-703 / ITAPaulo André Castro83
Exemplo - while
CE-703 / ITAPaulo André Castro84
Exemplo – do/while
15
CE-703 / ITAPaulo André Castro85
Exemplo - for
CE-703 / ITAPaulo André Castro86
Percorrendo todos os elementos de um array
CE-703 / ITAPaulo André Castro87
Percorrendo todos os elementos de um array
CE-703 / ITAPaulo André Castro88
Comando condicional - if
CE-703 / ITAPaulo André Castro89
Expressões Condicionais
CE-703 / ITAPaulo André Castro90
Exemplos
16
CE-703 / ITAPaulo André Castro91
Comparação de Strings
CE-703 / ITAPaulo André Castro92
Criando Arrays
CE-703 / ITAPaulo André Castro93
Arrays de várias dimensões
CE-703 / ITAPaulo André Castro94
Exemplo
CE-703 / ITAPaulo André Castro95
Resultado
CE-703 / ITAPaulo André Castro96
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
17
97
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:
CE-703 / ITAPaulo André Castro98
Diagrama Simplicado de Exceções
99
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
CE-703 / ITAPaulo André Castro100
Um exemplo de Try-catch
101
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
CE-703 / ITAPaulo André Castro102
Jogando exceções
18
CE-703 / ITAPaulo André Castro103
Estruturas de Dados no Java 2
CE-703 / ITAPaulo André Castro104
Collection Interfaces
CE-703 / ITAPaulo André Castro105
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
CE-703 / ITAPaulo André Castro106
Métodos úteis em Vector
CE-703 / ITAPaulo André Castro107
Utilizando Vector
CE-703 / ITAPaulo André Castro108
Métodos úteis em Hashtable
19
CE-703 / ITAPaulo André Castro109
Exemplo de Uso de um Hashtableimport 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);}
}}
CE-703 / ITAPaulo André Castro110
Resultado
� >three = 3
CE-703 / ITAPaulo André Castro111
Exemplo de Uso de uma Coleção Vectorimport 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);
}
}
}
CE-703 / ITAPaulo André Castro112
Resultado
>Linha 1
Linha 2
Linha 3
Linha 4
Linha 5
CE-703 / ITAPaulo André Castro113
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#
CE-703 / ITAPaulo André Castro114
Avanços em Collections no JDK 5.0
� Coleções genéricas:Vector<String> vetStrings=new Vector<String>();
� Laços de Iteração Aprimoradosfor(String element: vetStrings) {
System.out.println(element);
}
20
CE-703 / ITAPaulo André Castro115
Exemplo de Uso de uma Coleção Genéricaimport 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);
}
}
}
CE-703 / ITAPaulo André Castro116
Resultado
>Linha 1
Linha 2
Linha 3
Linha 4
Linha 5
CE-703 / ITAPaulo André Castro117
HashTable Genéricoimport 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);}
}}
CE-703 / ITAPaulo André Castro118
Resultado
� >three = 3
119
Classes Wrapper
� Todo tipo primitivo em Java, tem uma classe correspondente que pode encapsula-lo
120
Uso de Classes Wrapper
� Define constantes úteis, por exemplo:
� Conversão entre tipos de dados� Utilize parseXXX para fazer conversões:
21
CE-703 / ITAPaulo André Castro121
Outras conversões...
CE-703 / ITAPaulo André Castro122
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
CE-703 / ITAPaulo André Castro123
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
CE-703 / ITAPaulo André Castro124
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
CE-703 / ITAPaulo André Castro125
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
CE-703 / ITAPaulo André Castro126
Exemplo – [default]
22
CE-703 / ITAPaulo André Castro127
Sumário de modificadores de acesso
CE-703 / ITAPaulo André Castro128
Outros modificadores
CE-703 / ITAPaulo André Castro129
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;}
}
130
Formatando Texto� Números� Use DecimalFormat para formatação
� Nas versões mais novas, Java implementa um método printf, semelhante ao C/C++
� Abordagem DecimalFormat1. 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);
CE-703 / ITAPaulo André Castro131
Formatando Números
CE-703 / ITAPaulo André Castro132
Exemplo – Formatação de Números
23
CE-703 / ITAPaulo André Castro133
Resultado – Formatando Números
CE-703 / ITAPaulo André Castro134
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);
CE-703 / ITAPaulo André Castro135
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);
}
CE-703 / ITAPaulo André Castro136
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
CE-703 / ITAPaulo André Castro137
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.MONT H)+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.MIN UTE));
String second=Integer.toString(cal.get(Calendar.SEC OND));
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;
}
CE-703 / ITAPaulo André Castro138
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();
}
24
CE-703 / ITAPaulo André Castro139
� 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));
}
}
CE-703 / ITAPaulo André Castro140
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
CE-703 / ITAPaulo André Castro141
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)
CE-703 / ITAPaulo André Castro142
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
CE-703 / ITAPaulo André Castro143
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
CE-703 / ITAPaulo André Castro144
A classe File
25
CE-703 / ITAPaulo André Castro145
Métodos úteis em File
CE-703 / ITAPaulo André Castro146
Exemplo de File:Programa que lista o diretório do usuário
CE-703 / ITAPaulo André Castro147
Resultado
CE-703 / ITAPaulo André Castro148
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:
CE-703 / ITAPaulo André Castro149
Soluçãoimport 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");
}
} CE-703 / ITAPaulo André Castro150
Resultado
26
CE-703 / ITAPaulo André Castro151
Classes para escrever Texto
CE-703 / ITAPaulo André Castro152
Classes para escrever Texto
CE-703 / ITAPaulo André Castro153
Exemplo de Escrita de Arquivo de Texto
CE-703 / ITAPaulo André Castro154
Codificação de caracteres
CE-703 / ITAPaulo André Castro155
Classes de Leitura de Streams de Texto
CE-703 / ITAPaulo André Castro156
UCS Transformation Format – UTF 8
27
CE-703 / ITAPaulo André Castro157
Exemplo - FileReader
CE-703 / ITAPaulo André Castro158
Resultado - FileReader
CE-703 / ITAPaulo André Castro159
I/O em Arquivos (Streams) Binários
CE-703 / ITAPaulo André Castro160
Classes para Escrita em Streams Binárias
CE-703 / ITAPaulo André Castro161
Classes para Escrita em Streams Binárias
CE-703 / ITAPaulo André Castro162
Exemplo – Escrita em Arquivos Binários
28
CE-703 / ITAPaulo André Castro163
Classes para Leitura em Streams Binárias
CE-703 / ITAPaulo André Castro164
Classes para Leitura em Streams Binárias
CE-703 / ITAPaulo André Castro165
Exemplo – Leitura de Arquivos Binários
CE-703 / ITAPaulo André Castro166
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.
Introdução a Ambientes de Desenvolvimento Integrado
CE-703 / ITAPaulo André Castro168
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
29
CE-703 / ITAPaulo André Castro169
Eclipse IDE
CE-703 / ITAPaulo André Castro170
Criando Workspace
171
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
172
Criando Projetos – Passo 2
� Escolha� Nome do Projeto
� Projeto vazio ou criado a partir de código pré-existente
� JDK alvo
� Project Layout
173
Configuração do Projeto
� Escolha dos diretórios com código-fonte
� Bibliotecas utilizadas
� Projetos requeridos
� Ordem de importação/exportação
174
Opções de Projeto
� Criação de elementos do Projeto� Classes, interfaces, etc.
� Refactoring
� Propriedades,etc.
30
175
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.
CE-703 / ITAPaulo André Castro176
Alguns Exemplos de Programas
CE-703 / ITAPaulo André Castro177
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
CE-703 / ITAPaulo André Castro178
Exemplo 2
Compile e Execute o programa acima
CE-703 / ITAPaulo André Castro179
Inserindo argumentos para os programas através do Eclipse
• Menu Run | Run ...
•Tab Arguments
CE-703 / ITAPaulo André Castro180
Exemplo 3 – Usando Loops
31
CE-703 / ITAPaulo André Castro181
Exemplo 4 – Loops Aninhados
CE-703 / ITAPaulo André Castro182
Exemplo 5
CE-703 / ITAPaulo André Castro183
Exemplo 5
CE-703 / ITAPaulo André Castro184
Saída do Exemplo 5
CE-703 / ITAPaulo André Castro185
Onde estão as classes ? CLASSPATH
CE-703 / ITAPaulo André Castro186
Pacotes...
32
CE-703 / ITAPaulo André Castro187
Pacotes...
CE-703 / ITAPaulo André Castro188
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
CE-703 / ITAPaulo André Castro189
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();
CE-703 / ITAPaulo André Castro190
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
CE-703 / ITAPaulo André Castro191
Solução – Exercício 1 – Classe DataFileTest
public class DataFileTest
{ static void writeData(Employee[] e, PrintWriter os)
throws IOException{ os.println(e.length);
int i;
for (i = 0; i < e.length; i++)e[i].writeData(os);
}
static Employee[] readData(BufferedReader is)
throws IOException{ int n = Integer.parseInt(is.readLine());
Employee[] e = new Employee[n];int i;
for (i = 0; i < n; i++){ e[i] = new Employee();
e[i].readData(is);
}return e;
}
public static void main(String[] args){ Employee[] staff = new Employee[3];
staff[0] = new Employee("Harry Hacker", 35500, Format.getDate(1989,10,1));
staff[1] = new Employee("Carl Cracker", 75000, Format.getDate(1987,12,15));
staff[2] = new Employee("Tony Tester", 38000, Format.getDate(1990,3,15));
try{ PrintWriter os = new PrintWriter(new
FileWriter("employee.dat"));writeData(staff, os); os.close();
} catch(IOException e){ System.out.print("Error: " + e);
System.exit(1); }try
{ BufferedReader is = new BufferedReader(new FileReader("employee.dat"));
Employee[] in = readData(is);for (i = 0; i < in.length; i++) in[i].print();is.close();
} catch(IOException e){ System.out.print("Error: " + e); System.exit(1); } } }
CE-703 / ITAPaulo André Castro192
class Employee{ public Employee(String n, double s, Date d)
{ name = n;
salary = s;hireDay = d;
}public Employee() {}
public void print(){ System.out.println(name + " " + salary
+ " " + hireYear());
}public void raiseSalary(double byPercent)
{ salary *= 1 + byPercent / 100;}
public int hireYear(){ return Format.getYear(hireDay);
}
public void writeData(PrintWriter os) throws IOException{ os.print(name+ "|");
os.print( salary+ "|");os.print(Format.getYear(hireDay)+ "|");os.print(Format.getMonth(hireDay)+ "|");os.print(Format.getDayofMonth(hireDay)+ "\n");
}
public void readData(BufferedReader is) throws IOException{ String s = is.readLine();
StringTokenizer t = new StringTokenizer(s, "|");name = t.nextToken();salary = Double.parseDouble(t.nextToken());int y = Integer.parseInt(t.nextToken());int m = Integer.parseInt(t.nextToken());int d = Integer.parseInt(t.nextToken());hireDay = Format.getDate(y,m,d);
}
private String name;private double salary;private Date hireDay;
}
33
CE-703 / ITAPaulo André Castro193
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;}
CE-703 / ITAPaulo André Castro194
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
Multitarefa
CE-703 / ITAPaulo André Castro
MultithreadingSumário5.2.1 Introdução5.2.2 Estados de um Thread: Ciclo de vida de um Th read5.2..3 Prioridades de Thread Priorities and Thread Scheduling5.2.4 Creating and Executing Threads5.2.5 Thread Synchronization5.2.6 Producer/Consumer Relationship without Synch ronization5.2.7 Producer/Consumer Relationship with Synchron ization5.2.8 Daemon Threads5.2.9 Runnable Interface
CE-703 / ITAPaulo André Castro
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
CE-703 / ITAPaulo André Castro
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
34
CE-703 / ITAPaulo André Castro
Fig. 5.2.1 Thread life-cycle statechart diagram
Ready
Running
BlockedSleepingWaiting
start
notif
yno
tifyA
lltim
eout
exp
ires
inte
rrup
t
thread dispatch(assign a processor)
quantum expirationyield
sleep interval expires
interrupt
Born
I/O com
pletesacquire lock
interrupt
When a thread completes (returns from its run method), it reaches the Dead state (shown here as the final state)
CE-703 / ITAPaulo André Castro
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
CE-703 / ITAPaulo André Castro
Fig. 5.2.2 Thread priority scheduling example
Priority 9
Priority 8
Priority 7
Priority 10
Priority 6
Priority 5
Priority 4
Priority 3
Priority 2
Priority 1
A B
D
C
E F
G
H I
J K
Ready threads
Thread.MIN_PRIORITY
Thread.MAX_PRIORITY
Thread.NORM_PRIORITY
CE-703 / ITAPaulo André Castro
5.2.4 Creating and Executing Threads
� Sleep state� Thread method sleep called
� Thread sleeps for a set time interval then awakens
1 // Fig. 5.2.3: ThreadTester.java// Fig. 5.2.3: ThreadTester.java// Fig. 5.2.3: ThreadTester.java// Fig. 5.2.3: ThreadTester.java
2 // Multiple threads printing at different intervals.// Multiple threads printing at different intervals.// Multiple threads printing at different intervals.// Multiple threads printing at different intervals.
3
4 publicpublicpublicpublic classclassclassclass ThreadTester {ThreadTester {ThreadTester {ThreadTester {
5
6 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String [] args )main( String [] args )main( String [] args )main( String [] args )
7 {{{{
8 // create and name each thread// create and name each thread// create and name each thread// create and name each thread
9 PrintThread thread1 = PrintThread thread1 = PrintThread thread1 = PrintThread thread1 = newnewnewnew PrintThread( PrintThread( PrintThread( PrintThread( "thread1""thread1""thread1""thread1" ););););
10 PrintThread thread2 = PrintThread thread2 = PrintThread thread2 = PrintThread thread2 = newnewnewnew PrintThread( PrintThread( PrintThread( PrintThread( "thread2""thread2""thread2""thread2" ););););
11 PrintThread thread3 = PrintThread thread3 = PrintThread thread3 = PrintThread thread3 = newnewnewnew PrintThread( PrintThread( PrintThread( PrintThread( "thread3""thread3""thread3""thread3" ););););
12
13 System.err.println( System.err.println( System.err.println( System.err.println( "Starting threads""Starting threads""Starting threads""Starting threads" ););););
14
15 thread1.start(); thread1.start(); thread1.start(); thread1.start(); // start thread1 and place it in ready state// start thread1 and place it in ready state// start thread1 and place it in ready state// start thread1 and place it in ready state
16 thread2.start(); thread2.start(); thread2.start(); thread2.start(); // start thread2 and place it in ready state// start thread2 and place it in ready state// start thread2 and place it in ready state// start thread2 and place it in ready state
17 thread3.start(); thread3.start(); thread3.start(); thread3.start(); // start thread3 and place it in ready state// start thread3 and place it in ready state// start thread3 and place it in ready state// start thread3 and place it in ready state
18
19 System.err.println( System.err.println( System.err.println( System.err.println( "Threads started, main ends"Threads started, main ends"Threads started, main ends"Threads started, main ends\\\\n"n"n"n" ););););
20
21 } } } } // end main// end main// end main// end main
22
23 } } } } // end class ThreadTester// end class ThreadTester// end class ThreadTester// end class ThreadTester
24
create four PrintThreads
call start methods
25 // class PrintThread controls thread execution // class PrintThread controls thread execution // class PrintThread controls thread execution // class PrintThread controls thread execution
26 classclassclassclass PrintThread PrintThread PrintThread PrintThread extendsextendsextendsextends Thread { Thread { Thread { Thread {
27 privateprivateprivateprivate intintintint sleepTime; sleepTime; sleepTime; sleepTime;
28
29 // assign name to thread by calling superclass constructor// assign name to thread by calling superclass constructor// assign name to thread by calling superclass constructor// assign name to thread by calling superclass constructor
30 publicpublicpublicpublic PrintThread( String name ) PrintThread( String name ) PrintThread( String name ) PrintThread( String name )
31 {{{{
32 supersupersupersuper( name );( name );( name );( name );
33
34 // pick random sleep time between 0 and 5 seconds// pick random sleep time between 0 and 5 seconds// pick random sleep time between 0 and 5 seconds// pick random sleep time between 0 and 5 seconds
35 sleepTime = ( sleepTime = ( sleepTime = ( sleepTime = ( intintintint ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * 5001500150015001 ););););
36 } } } }
37
38 // method run is the code to be executed by new thread // method run is the code to be executed by new thread // method run is the code to be executed by new thread // method run is the code to be executed by new thread
39 publicpublicpublicpublic voidvoidvoidvoid run() run() run() run()
40 { { { {
41 // put thread to sleep for sleepTime amount of time // put thread to sleep for sleepTime amount of time // put thread to sleep for sleepTime amount of time // put thread to sleep for sleepTime amount of time
42 trytrytrytry { { { {
43 System.err.println( System.err.println( System.err.println( System.err.println(
44 getName() + getName() + getName() + getName() + " going to sleep for "" going to sleep for "" going to sleep for "" going to sleep for " + sleepTime ); + sleepTime ); + sleepTime ); + sleepTime );
45
46 Thread.sleep( sleepTime ); Thread.sleep( sleepTime ); Thread.sleep( sleepTime ); Thread.sleep( sleepTime );
47 } } } }
48
PrintThread extends Thread
Constructor initializes sleepTime
When the thread enters the running state, run is called
35
49 // if thread interrupted during sleep, print stack trace// if thread interrupted during sleep, print stack trace// if thread interrupted during sleep, print stack trace// if thread interrupted during sleep, print stack trace
50 catchcatchcatchcatch ( InterruptedException exception ) { ( InterruptedException exception ) { ( InterruptedException exception ) { ( InterruptedException exception ) {
51 exception.printStackTrace(); exception.printStackTrace(); exception.printStackTrace(); exception.printStackTrace();
52 } } } }
53
54 // print thread name // print thread name // print thread name // print thread name
55 System.err.println( getName() + System.err.println( getName() + System.err.println( getName() + System.err.println( getName() + " done sleeping"" done sleeping"" done sleeping"" done sleeping" ); ); ); );
56
57 } } } } // end method run // end method run // end method run // end method run
58
59 } } } } // end class PrintThread// end class PrintThread// end class PrintThread// end class PrintThread
Starting threadsThreads started, main ends
thread1 going to sleep for 1217thread2 going to sleep for 3989thread3 going to sleep for 662thread3 done sleepingthread1 done sleepingthread2 done sleeping
Starting threadsStarting threadsStarting threadsStarting threads
thread1 going to sleep for 314thread1 going to sleep for 314thread1 going to sleep for 314thread1 going to sleep for 314
thread2 going to sleep for 1990thread2 going to sleep for 1990thread2 going to sleep for 1990thread2 going to sleep for 1990
Threads started, main endsThreads started, main endsThreads started, main endsThreads started, main ends
thread3 going to sleep for 3016thread3 going to sleep for 3016thread3 going to sleep for 3016thread3 going to sleep for 3016
thread1 done sleepingthread1 done sleepingthread1 done sleepingthread1 done sleeping
thread2 done sleepingthread2 done sleepingthread2 done sleepingthread2 done sleeping
thread3 done sleepingthread3 done sleepingthread3 done sleepingthread3 done sleeping
CE-703 / ITAPaulo André Castro
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
CE-703 / ITAPaulo André Castro
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
Consumer reads Consumer reads Consumer reads Consumer reads ----1111
Producer writes 1Producer writes 1Producer writes 1Producer writes 1
Consumer reads 1Consumer reads 1Consumer reads 1Consumer reads 1
Consumer reads 1Consumer reads 1Consumer reads 1Consumer reads 1
Consumer reads 1Consumer reads 1Consumer reads 1Consumer reads 1
Consumer read values totaling: 2.Consumer read values totaling: 2.Consumer read values totaling: 2.Consumer read values totaling: 2.
Terminating Consumer.Terminating Consumer.Terminating Consumer.Terminating Consumer.
Producer writes 2Producer writes 2Producer writes 2Producer writes 2
Producer writes 3Producer writes 3Producer writes 3Producer writes 3
Producer writes 4Producer writes 4Producer writes 4Producer writes 4
Producer done producing.Producer done producing.Producer done producing.Producer done producing.
Terminating Producer.Terminating Producer.Terminating Producer.Terminating Producer.
Producer writes 1Producer writes 1Producer writes 1Producer writes 1Producer writes 2Producer writes 2Producer writes 2Producer writes 2Consumer reads 2Consumer reads 2Consumer reads 2Consumer reads 2Producer writes 3Producer writes 3Producer writes 3Producer writes 3Consumer reads 3Consumer reads 3Consumer reads 3Consumer reads 3Producer writes 4Producer writes 4Producer writes 4Producer writes 4Producer done producing.Producer done producing.Producer done producing.Producer done producing.Terminating Producer.Terminating Producer.Terminating Producer.Terminating Producer.Consumer reads 4Consumer reads 4Consumer reads 4Consumer reads 4Consumer reads 4Consumer reads 4Consumer reads 4Consumer reads 4Consumer read values totaling: 13.Consumer read values totaling: 13.Consumer read values totaling: 13.Consumer read values totaling: 13.Terminating Consumer.Terminating Consumer.Terminating Consumer.Terminating Consumer.
Exemplo de Saída: SharedBuffer
Producer writes 1Producer writes 1Producer writes 1Producer writes 1
Consumer reads 1Consumer reads 1Consumer reads 1Consumer reads 1
Producer writes 2Producer writes 2Producer writes 2Producer writes 2
Consumer reads 2Consumer reads 2Consumer reads 2Consumer reads 2
Producer writes 3Producer writes 3Producer writes 3Producer writes 3
Consumer reads 3Consumer reads 3Consumer reads 3Consumer reads 3
Producer writes 4Producer writes 4Producer writes 4Producer writes 4
Producer done producing.Producer done producing.Producer done producing.Producer done producing.
Terminating Producer.Terminating Producer.Terminating Producer.Terminating Producer.
Consumer reads 4Consumer reads 4Consumer reads 4Consumer reads 4
Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.
Terminating Consumer.Terminating Consumer.Terminating Consumer.Terminating Consumer.
36
1 // Buffer.java// Buffer.java// Buffer.java// Buffer.java
2 // Buffer interface specifies methods called by Producer and Consumer.// Buffer interface specifies methods called by Producer and Consumer.// Buffer interface specifies methods called by Producer and Consumer.// Buffer interface specifies methods called by Producer and Consumer.
3
4 publicpublicpublicpublic interfaceinterfaceinterfaceinterface Buffer {Buffer {Buffer {Buffer {
5 publicpublicpublicpublic voidvoidvoidvoid set( set( set( set( intintintint value ); value ); value ); value ); // place value into Buffer// place value into Buffer// place value into Buffer// place value into Buffer
6 publicpublicpublicpublic intintintint get(); get(); get(); get(); // return value from Buffer// return value from Buffer// return value from Buffer// return value from Buffer
7 }}}}
1 // Fig. 5.2.5: Producer.java// Fig. 5.2.5: Producer.java// Fig. 5.2.5: Producer.java// Fig. 5.2.5: Producer.java
2 // Producer's run method controls a thread that// Producer's run method controls a thread that// Producer's run method controls a thread that// Producer's run method controls a thread that
3 // stores values from 1 to 4 in sharedLocation.// stores values from 1 to 4 in sharedLocation.// stores values from 1 to 4 in sharedLocation.// stores values from 1 to 4 in sharedLocation.
4
5 publicpublicpublicpublic classclassclassclass Producer Producer Producer Producer extendsextendsextendsextends Thread {Thread {Thread {Thread {
6 privateprivateprivateprivate Buffer sharedLocation; Buffer sharedLocation; Buffer sharedLocation; Buffer sharedLocation; // reference to shared object// reference to shared object// reference to shared object// reference to shared object
7
8 // constructor// constructor// constructor// constructor
9 publicpublicpublicpublic Producer( Buffer shared )Producer( Buffer shared )Producer( Buffer shared )Producer( Buffer shared )
10 {{{{
11 supersupersupersuper( ( ( ( "Producer""Producer""Producer""Producer" ););););
12 sharedLocation = shared;sharedLocation = shared;sharedLocation = shared;sharedLocation = shared;
13 }}}}
14
15 // store values from 1 to 4 in sharedLocation// store values from 1 to 4 in sharedLocation// store values from 1 to 4 in sharedLocation// store values from 1 to 4 in sharedLocation
16 publicpublicpublicpublic voidvoidvoidvoid run()run()run()run()
17 {{{{
18 forforforfor ( ( ( ( intintintint count = count = count = count = 1111; count <= ; count <= ; count <= ; count <= 4444; count++ ) { ; count++ ) { ; count++ ) { ; count++ ) {
19 int sum=0;int sum=0;int sum=0;int sum=0;
20 // sleep 0 to 3 seconds, then place value in Buffer// sleep 0 to 3 seconds, then place value in Buffer// sleep 0 to 3 seconds, then place value in Buffer// sleep 0 to 3 seconds, then place value in Buffer
21 trytrytrytry {{{{
22 Thread.sleep( ( Thread.sleep( ( Thread.sleep( ( Thread.sleep( ( intintintint ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * 3001300130013001 ) ); sum+=count;) ); sum+=count;) ); sum+=count;) ); sum+=count;
23 sharedLocation.set( count ); sharedLocation.set( count ); sharedLocation.set( count ); sharedLocation.set( count );
24 }}}}
25
Producer extends Thread
This is a shared object
Method run is overridden
The thread goes to sleep, then the buffer is set
26 // if sleeping thread interrupted, print stack trace// if sleeping thread interrupted, print stack trace// if sleeping thread interrupted, print stack trace// if sleeping thread interrupted, print stack trace
27 catchcatchcatchcatch ( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {
28 exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();
29 }}}}
30
31 } } } } // end for// end for// end for// end for
32
33 System.err.println( getName() + System.err.println( getName() + System.err.println( getName() + System.err.println( getName() + " done producing totaling “+sum" done producing totaling “+sum" done producing totaling “+sum" done producing totaling “+sum + + + +
34 """"\\\\nTerminating "nTerminating "nTerminating "nTerminating " + getName() + + getName() + + getName() + + getName() + ".""."".""."););););
35
36 } } } } // end method run// end method run// end method run// end method run
37
38 } } } } // end class Producer// end class Producer// end class Producer// end class Producer
1 // Fig. 5.2.6: Consumer.java// Fig. 5.2.6: Consumer.java// Fig. 5.2.6: Consumer.java// Fig. 5.2.6: Consumer.java
2 // Consumer's run method controls a thread that loops four// Consumer's run method controls a thread that loops four// Consumer's run method controls a thread that loops four// Consumer's run method controls a thread that loops four
3 // times and reads a value from sharedLocation each time.// times and reads a value from sharedLocation each time.// times and reads a value from sharedLocation each time.// times and reads a value from sharedLocation each time.
4
5 publicpublicpublicpublic classclassclassclass Consumer Consumer Consumer Consumer extendsextendsextendsextends Thread { Thread { Thread { Thread {
6 privateprivateprivateprivate Buffer sharedLocation; Buffer sharedLocation; Buffer sharedLocation; Buffer sharedLocation; // reference to shared object// reference to shared object// reference to shared object// reference to shared object
7
8 // constructor// constructor// constructor// constructor
9 publicpublicpublicpublic Consumer( Buffer shared )Consumer( Buffer shared )Consumer( Buffer shared )Consumer( Buffer shared )
10 {{{{
11 supersupersupersuper( ( ( ( "Consumer""Consumer""Consumer""Consumer" ););););
12 sharedLocation = shared;sharedLocation = shared;sharedLocation = shared;sharedLocation = shared;
13 }}}}
14
15 // read sharedLocation's value four times and sum the values// read sharedLocation's value four times and sum the values// read sharedLocation's value four times and sum the values// read sharedLocation's value four times and sum the values
16 publicpublicpublicpublic voidvoidvoidvoid run()run()run()run()
17 {{{{
18 intintintint sum = sum = sum = sum = 0000;;;;
19
20 forforforfor ( ( ( ( intintintint count = count = count = count = 1111; count <= ; count <= ; count <= ; count <= 4444; count++ ) {; count++ ) {; count++ ) {; count++ ) {
21
22 // sleep 0 to 3 seconds, read value from Buffer and add to sum// sleep 0 to 3 seconds, read value from Buffer and add to sum// sleep 0 to 3 seconds, read value from Buffer and add to sum// sleep 0 to 3 seconds, read value from Buffer and add to sum
23 trytrytrytry {{{{
24 Thread.sleep( ( Thread.sleep( ( Thread.sleep( ( Thread.sleep( ( intintintint ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * 3001300130013001 ) ); ) ); ) ); ) );
25 sum += sharedLocation.get();sum += sharedLocation.get();sum += sharedLocation.get();sum += sharedLocation.get();
26 }}}}
27
Consumer extends Thread
This is a shared object
Method run is overridden
The thread goes to sleep, then the buffer is read
28 // if sleeping thread interrupted, print stack trace// if sleeping thread interrupted, print stack trace// if sleeping thread interrupted, print stack trace// if sleeping thread interrupted, print stack trace
29 catchcatchcatchcatch ( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {
30 exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();
31 }}}}
32 }}}}
33
34 System.err.println( getName() + System.err.println( getName() + System.err.println( getName() + System.err.println( getName() + " read values totaling: "" read values totaling: "" read values totaling: "" read values totaling: " + sum + + sum + + sum + + sum +
35 ".".".".\\\\nTerminating "nTerminating "nTerminating "nTerminating " + getName() + + getName() + + getName() + + getName() + ".""."".""."););););
36
37 } } } } // end method run// end method run// end method run// end method run
38
39 } } } } // end class Consumer// end class Consumer// end class Consumer// end class Consumer
1 // UnsynchronizedBuffer.java// UnsynchronizedBuffer.java// UnsynchronizedBuffer.java// UnsynchronizedBuffer.java
2 // UnsynchronizedBuffer represents a single shared integer.// UnsynchronizedBuffer represents a single shared integer.// UnsynchronizedBuffer represents a single shared integer.// UnsynchronizedBuffer represents a single shared integer.
3
4 publicpublicpublicpublic classclassclassclass UnsynchronizedBuffer UnsynchronizedBuffer UnsynchronizedBuffer UnsynchronizedBuffer implementsimplementsimplementsimplements Buffer {Buffer {Buffer {Buffer {
5 privateprivateprivateprivate intintintint buffer = buffer = buffer = buffer = ----1111; ; ; ; // shared by producer and consumer threads// shared by producer and consumer threads// shared by producer and consumer threads// shared by producer and consumer threads
6
7 // place value into buffer// place value into buffer// place value into buffer// place value into buffer
8 publicpublicpublicpublic voidvoidvoidvoid set( set( set( set( intintintint value )value )value )value )
9 {{{{
10 System.err.println( Thread.currentThread().getName() +System.err.println( Thread.currentThread().getName() +System.err.println( Thread.currentThread().getName() +System.err.println( Thread.currentThread().getName() +
11 " writes "" writes "" writes "" writes " + value );+ value );+ value );+ value );
12
13 buffer = value;buffer = value;buffer = value;buffer = value;
14 }}}}
15
16 // return value from buffer// return value from buffer// return value from buffer// return value from buffer
17 publicpublicpublicpublic intintintint get()get()get()get()
18 {{{{
19 System.err.println( Thread.currentThread().getName() +System.err.println( Thread.currentThread().getName() +System.err.println( Thread.currentThread().getName() +System.err.println( Thread.currentThread().getName() +
20 " reads "" reads "" reads "" reads " + buffer );+ buffer );+ buffer );+ buffer );
21
22 returnreturnreturnreturn buffer; buffer; buffer; buffer;
23 }}}}
24
25 } } } } // end class UnsynchronizedBuffer// end class UnsynchronizedBuffer// end class UnsynchronizedBuffer// end class UnsynchronizedBuffer
This class implements the Buffer interface
The data is a single integer
This method sets the value in the buffer
This method reads the value in the buffer
37
1 // SharedBufferTest.java// SharedBufferTest.java// SharedBufferTest.java// SharedBufferTest.java
2 // SharedBufferTest creates producer and consumer threads.// SharedBufferTest creates producer and consumer threads.// SharedBufferTest creates producer and consumer threads.// SharedBufferTest creates producer and consumer threads.
3
4 publicpublicpublicpublic classclassclassclass SharedBufferTest {SharedBufferTest {SharedBufferTest {SharedBufferTest {
5
6 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String [] args )main( String [] args )main( String [] args )main( String [] args )
7 {{{{
8 // create shared object used by threads// create shared object used by threads// create shared object used by threads// create shared object used by threads
9 Buffer sharedLocation = Buffer sharedLocation = Buffer sharedLocation = Buffer sharedLocation = newnewnewnew UnsynchronizedBuffer();UnsynchronizedBuffer();UnsynchronizedBuffer();UnsynchronizedBuffer();
10
11 // create producer and consumer objects// create producer and consumer objects// create producer and consumer objects// create producer and consumer objects
12 Producer producer = Producer producer = Producer producer = Producer producer = newnewnewnew Producer( sharedLocation );Producer( sharedLocation );Producer( sharedLocation );Producer( sharedLocation );
13 Consumer consumer = Consumer consumer = Consumer consumer = Consumer consumer = newnewnewnew Consumer( sharedLocation );Consumer( sharedLocation );Consumer( sharedLocation );Consumer( sharedLocation );
14
15 producer.start(); producer.start(); producer.start(); producer.start(); // start producer thread// start producer thread// start producer thread// start producer thread
16 consumer.start(); consumer.start(); consumer.start(); consumer.start(); // start consumer thread// start consumer thread// start consumer thread// start consumer thread
17
18 } } } } // end main// end main// end main// end main
19
20 } } } } // end class SharedCell// end class SharedCell// end class SharedCell// end class SharedCell
Create a Buffer object
Create a Producer and a Consumer
Start the Producer and Consumer threads
CE-703 / ITAPaulo André Castro
5.2.7 Producer/Consumer Relationship with Synchronization
� Synchronize threads to ensure correct data
� Exemplo Sincronizado: SynchronizedBuffer
1 // Fig. 5.2.9: SynchronizedBuffer.java// Fig. 5.2.9: SynchronizedBuffer.java// Fig. 5.2.9: SynchronizedBuffer.java// Fig. 5.2.9: SynchronizedBuffer.java
2 // SynchronizedBuffer synchronizes access to a single shared integer.// SynchronizedBuffer synchronizes access to a single shared integer.// SynchronizedBuffer synchronizes access to a single shared integer.// SynchronizedBuffer synchronizes access to a single shared integer.
3
4 publicpublicpublicpublic classclassclassclass SynchronizedBuffer SynchronizedBuffer SynchronizedBuffer SynchronizedBuffer implementsimplementsimplementsimplements Buffer {Buffer {Buffer {Buffer {
5 privateprivateprivateprivate intintintint buffer = buffer = buffer = buffer = ----1111; ; ; ; // shared by producer and consumer threads// shared by producer and consumer threads// shared by producer and consumer threads// shared by producer and consumer threads
6 privateprivateprivateprivate intintintint occupiedBufferCount = occupiedBufferCount = occupiedBufferCount = occupiedBufferCount = 0000; ; ; ; // count of occupied buffers// count of occupied buffers// count of occupied buffers// count of occupied buffers
7
8 // place value into buffer// place value into buffer// place value into buffer// place value into buffer
9 publicpublicpublicpublic synchronizedsynchronizedsynchronizedsynchronized voidvoidvoidvoid set( set( set( set( intintintint value )value )value )value )
10 {{{{
11 // for output purposes, get name of thread that called this method// for output purposes, get name of thread that called this method// for output purposes, get name of thread that called this method// for output purposes, get name of thread that called this method
12 String name = Thread.currentThread().getName();String name = Thread.currentThread().getName();String name = Thread.currentThread().getName();String name = Thread.currentThread().getName();
13
14 // while there are no empty locations, place thread in waiting state// while there are no empty locations, place thread in waiting state// while there are no empty locations, place thread in waiting state// while there are no empty locations, place thread in waiting state
15 whilewhilewhilewhile ( occupiedBufferCount == ( occupiedBufferCount == ( occupiedBufferCount == ( occupiedBufferCount == 1111 ) {) {) {) {
16
17 // output thread information and buffer information, then wait// output thread information and buffer information, then wait// output thread information and buffer information, then wait// output thread information and buffer information, then wait
18 trytrytrytry {{{{
19 System.err.println( name + System.err.println( name + System.err.println( name + System.err.println( name + " tries to write."" tries to write."" tries to write."" tries to write." ););););
20 displayState( displayState( displayState( displayState( "Buffer full. ""Buffer full. ""Buffer full. ""Buffer full. " + name + + name + + name + + name + " waits."" waits."" waits."" waits." ););););
21 wait();wait();wait();wait();
22 }}}}
23
24 // if waiting thread interrupted, print stack trace// if waiting thread interrupted, print stack trace// if waiting thread interrupted, print stack trace// if waiting thread interrupted, print stack trace
25 catchcatchcatchcatch ( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {
26 exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();
27 }}}}
This class implements the Buffer interface
Remember the number of filled spaces
Get the name of the thread
Wait while the buffer is filled
Method set is declared synchronized
28
29 } } } } // end while// end while// end while// end while
30
31 buffer = value; buffer = value; buffer = value; buffer = value; // set new buffer value// set new buffer value// set new buffer value// set new buffer value
32
33 // indicate producer cannot store another value// indicate producer cannot store another value// indicate producer cannot store another value// indicate producer cannot store another value
34 // until consumer retrieves current buffer value// until consumer retrieves current buffer value// until consumer retrieves current buffer value// until consumer retrieves current buffer value
35 ++occupiedBufferCount;++occupiedBufferCount;++occupiedBufferCount;++occupiedBufferCount;
36
37 displayState( name + displayState( name + displayState( name + displayState( name + " writes "" writes "" writes "" writes " + buffer );+ buffer );+ buffer );+ buffer );
38
39 notify(); notify(); notify(); notify(); // tell waiting thread to enter ready state// tell waiting thread to enter ready state// tell waiting thread to enter ready state// tell waiting thread to enter ready state
40
41 } } } } // end method set; releases lock on SynchronizedBuffer // end method set; releases lock on SynchronizedBuffer // end method set; releases lock on SynchronizedBuffer // end method set; releases lock on SynchronizedBuffer
42
43 // return value from buffer// return value from buffer// return value from buffer// return value from buffer
44 publicpublicpublicpublic synchronizedsynchronizedsynchronizedsynchronized intintintint get()get()get()get()
45 {{{{
46 // for output purposes, get name of thread that called this method// for output purposes, get name of thread that called this method// for output purposes, get name of thread that called this method// for output purposes, get name of thread that called this method
47 String name = Thread.currentThread().getName();String name = Thread.currentThread().getName();String name = Thread.currentThread().getName();String name = Thread.currentThread().getName();
48
Write to the buffer
Increment the buffer count
Alert a waiting thread
Get the name of the thread
Method get is declared synchronized
49 // while no data to read, place thread in waiting state// while no data to read, place thread in waiting state// while no data to read, place thread in waiting state// while no data to read, place thread in waiting state
50 whilewhilewhilewhile ( occupiedBufferCount == ( occupiedBufferCount == ( occupiedBufferCount == ( occupiedBufferCount == 0000 ) {) {) {) {
51
52 // output thread information and buffer information, then wait// output thread information and buffer information, then wait// output thread information and buffer information, then wait// output thread information and buffer information, then wait
53 trytrytrytry {{{{
54 System.err.println( name + System.err.println( name + System.err.println( name + System.err.println( name + " tries to read."" tries to read."" tries to read."" tries to read." ););););
55 displayState( displayState( displayState( displayState( "Buffer empty. ""Buffer empty. ""Buffer empty. ""Buffer empty. " + name + + name + + name + + name + " waits."" waits."" waits."" waits." ););););
56 wait();wait();wait();wait();
57 }}}}
58
59 // if waiting thread interrupted, print stack trace// if waiting thread interrupted, print stack trace// if waiting thread interrupted, print stack trace// if waiting thread interrupted, print stack trace
60 catchcatchcatchcatch ( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {
61 exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();
62 }}}}
63
64 } } } } // end while// end while// end while// end while
65
66 // indicate that producer can store another value // indicate that producer can store another value // indicate that producer can store another value // indicate that producer can store another value
67 // because consumer just retrieved buffer value// because consumer just retrieved buffer value// because consumer just retrieved buffer value// because consumer just retrieved buffer value
68 --------occupiedBufferCount;occupiedBufferCount;occupiedBufferCount;occupiedBufferCount;
69
70 displayState( name + displayState( name + displayState( name + displayState( name + " reads "" reads "" reads "" reads " + buffer );+ buffer );+ buffer );+ buffer );
71
72 notify(); notify(); notify(); notify(); // tell waiting thread to become ready to execute// tell waiting thread to become ready to execute// tell waiting thread to become ready to execute// tell waiting thread to become ready to execute
73
74 returnreturnreturnreturn buffer;buffer;buffer;buffer;
Wait while the buffer is empty
Decrement the buffer count
Alert a waiting thread
Return the buffer
75
76 } } } } // end method get; releases lock on SynchronizedBuffer // end method get; releases lock on SynchronizedBuffer // end method get; releases lock on SynchronizedBuffer // end method get; releases lock on SynchronizedBuffer
77
78 // display current operation and buffer state// display current operation and buffer state// display current operation and buffer state// display current operation and buffer state
79 publicpublicpublicpublic voidvoidvoidvoid displayState( String operation )displayState( String operation )displayState( String operation )displayState( String operation )
80 {{{{
81 StringBuffer outputLine = StringBuffer outputLine = StringBuffer outputLine = StringBuffer outputLine = newnewnewnew StringBuffer( operation );StringBuffer( operation );StringBuffer( operation );StringBuffer( operation );
82 outputLine.setLength( outputLine.setLength( outputLine.setLength( outputLine.setLength( 40404040 ););););
83 outputLine.append( buffer + outputLine.append( buffer + outputLine.append( buffer + outputLine.append( buffer + """"\\\\tttt\\\\t"t"t"t" + occupiedBufferCount );+ occupiedBufferCount );+ occupiedBufferCount );+ occupiedBufferCount );
84 System.err.println( outputLine );System.err.println( outputLine );System.err.println( outputLine );System.err.println( outputLine );
85 System.err.println();System.err.println();System.err.println();System.err.println();
86 }}}}
87
88 } } } } // end class SynchronizedBuffer// end class SynchronizedBuffer// end class SynchronizedBuffer// end class SynchronizedBuffer
38
1 // SharedBufferTest2.java// SharedBufferTest2.java// SharedBufferTest2.java// SharedBufferTest2.java
2 // SharedBufferTest2creates producer and consumer threads.// SharedBufferTest2creates producer and consumer threads.// SharedBufferTest2creates producer and consumer threads.// SharedBufferTest2creates producer and consumer threads.
3
4 publicpublicpublicpublic classclassclassclass SharedBufferTest2 {SharedBufferTest2 {SharedBufferTest2 {SharedBufferTest2 {
5
6 publicpublicpublicpublic staticstaticstaticstatic voidvoidvoidvoid main( String [] args )main( String [] args )main( String [] args )main( String [] args )
7 {{{{
8 // create shared object used by threads; we use a SynchronizedBuffer// create shared object used by threads; we use a SynchronizedBuffer// create shared object used by threads; we use a SynchronizedBuffer// create shared object used by threads; we use a SynchronizedBuffer
9 // reference rather than a Buffer reference so we can invoke // reference rather than a Buffer reference so we can invoke // reference rather than a Buffer reference so we can invoke // reference rather than a Buffer reference so we can invoke
10 // SynchronizedBuffer method displayState from main// SynchronizedBuffer method displayState from main// SynchronizedBuffer method displayState from main// SynchronizedBuffer method displayState from main
11 SynchronizedBuffer sharedLocation = SynchronizedBuffer sharedLocation = SynchronizedBuffer sharedLocation = SynchronizedBuffer sharedLocation = newnewnewnew SynchronizedBuffer();SynchronizedBuffer();SynchronizedBuffer();SynchronizedBuffer();
12
13 // Display column heads for output// Display column heads for output// Display column heads for output// Display column heads for output
14 StringBuffer columnHeads = StringBuffer columnHeads = StringBuffer columnHeads = StringBuffer columnHeads = newnewnewnew StringBuffer( StringBuffer( StringBuffer( StringBuffer( "Operation""Operation""Operation""Operation" ););););
15 columnHeads.setLength( columnHeads.setLength( columnHeads.setLength( columnHeads.setLength( 40404040 ););););
16 columnHeads.append( columnHeads.append( columnHeads.append( columnHeads.append( "Buffer"Buffer"Buffer"Buffer\\\\tttt\\\\tOccupied Count"tOccupied Count"tOccupied Count"tOccupied Count" ););););
17 System.err.println( columnHeads );System.err.println( columnHeads );System.err.println( columnHeads );System.err.println( columnHeads );
18 System.err.println();System.err.println();System.err.println();System.err.println();
19 sharedLocation.displayState( sharedLocation.displayState( sharedLocation.displayState( sharedLocation.displayState( "Initial State""Initial State""Initial State""Initial State" ););););
20
21 // create producer and consumer objects// create producer and consumer objects// create producer and consumer objects// create producer and consumer objects
22 Producer producer = Producer producer = Producer producer = Producer producer = newnewnewnew Producer( sharedLocation );Producer( sharedLocation );Producer( sharedLocation );Producer( sharedLocation );
23 Consumer consumer = Consumer consumer = Consumer consumer = Consumer consumer = newnewnewnew Consumer( sharedLocation );Consumer( sharedLocation );Consumer( sharedLocation );Consumer( sharedLocation );
24
Create a Buffer object
Output initial state
Create a Producer and a Consumer
25 producer.start(); producer.start(); producer.start(); producer.start(); // start producer thread// start producer thread// start producer thread// start producer thread
26 consumer.start(); consumer.start(); consumer.start(); consumer.start(); // start consumer thread// start consumer thread// start consumer thread// start consumer thread
27
28 } } } } // end main// end main// end main// end main
29
30 } } } } // end class SharedBufferTest2// end class SharedBufferTest2// end class SharedBufferTest2// 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
Start the Producer and Consumer threads
Consumer reads 3 3 0Consumer reads 3 3 0Consumer reads 3 3 0Consumer reads 3 3 0
Consumer tries to read.Consumer tries to read.Consumer tries to read.Consumer tries to read.
Buffer empty. Consumer waits. 3 0Buffer empty. Consumer waits. 3 0Buffer empty. Consumer waits. 3 0Buffer empty. Consumer waits. 3 0
Producer writes 4 4 1Producer writes 4 4 1Producer writes 4 4 1Producer writes 4 4 1
Consumer reads 4 4 0Consumer reads 4 4 0Consumer reads 4 4 0Consumer reads 4 4 0
Producer done producing.Producer done producing.Producer done producing.Producer done producing.
Terminating Producer.Terminating Producer.Terminating Producer.Terminating Producer.
Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.
Terminating Consumer.Terminating Consumer.Terminating Consumer.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.Producer tries to write.Producer tries to write.Producer tries to write.
Buffer full. Producer waits. 2 1Buffer full. Producer waits. 2 1Buffer full. Producer waits. 2 1Buffer full. Producer waits. 2 1
Consumer reads 2 2 0Consumer reads 2 2 0Consumer reads 2 2 0Consumer reads 2 2 0
Producer writes 3 3 1Producer writes 3 3 1Producer writes 3 3 1Producer writes 3 3 1
Consumer reads 3 3 0Consumer reads 3 3 0Consumer reads 3 3 0Consumer reads 3 3 0
Producer writes 4 4 1Producer writes 4 4 1Producer writes 4 4 1Producer writes 4 4 1
Producer done producing.Producer done producing.Producer done producing.Producer done producing.
Terminating Producer.Terminating Producer.Terminating Producer.Terminating Producer.
Consumer reads 4 4 0Consumer reads 4 4 0Consumer reads 4 4 0Consumer reads 4 4 0
Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.
Terminating Consumer.Terminating Consumer.Terminating Consumer.Terminating Consumer.Operation 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 0Consumer reads 2 2 0Consumer reads 2 2 0Consumer reads 2 2 0
Producer writes 3 3 1Producer writes 3 3 1Producer writes 3 3 1Producer writes 3 3 1
Consumer reads 3 3 0Consumer reads 3 3 0Consumer reads 3 3 0Consumer reads 3 3 0
Producer writes 4 4 1Producer writes 4 4 1Producer writes 4 4 1Producer writes 4 4 1
Producer done producing.Producer done producing.Producer done producing.Producer done producing.
Terminating Producer.Terminating Producer.Terminating Producer.Terminating Producer.
Consumer reads 4 4 0Consumer reads 4 4 0Consumer reads 4 4 0Consumer reads 4 4 0
Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.Consumer read values totaling: 10.
Terminating Consumer.Terminating Consumer.Terminating Consumer.Terminating Consumer.
CE-703 / ITAPaulo André Castro
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);
39
CE-703 / ITAPaulo André Castro
5.2.10 Runnable Interface
� A class cannot extend more than one class
� Implement Runnable for multithreading support
� Exemplo: RandomCharacters.java
1 // RandomCharacters.java// RandomCharacters.java// RandomCharacters.java// RandomCharacters.java
2 // Class RandomCharacters demonstrates the Runnable interface// Class RandomCharacters demonstrates the Runnable interface// Class RandomCharacters demonstrates the Runnable interface// Class RandomCharacters demonstrates the Runnable interface
3 importimportimportimport java.awt.*;java.awt.*;java.awt.*;java.awt.*;
4 importimportimportimport java.awt.event.*;java.awt.event.*;java.awt.event.*;java.awt.event.*;
5 importimportimportimport javax.swing.*;javax.swing.*;javax.swing.*;javax.swing.*;
6
7 publicpublicpublicpublic classclassclassclass RandomCharacters RandomCharacters RandomCharacters RandomCharacters extendsextendsextendsextends JApplet JApplet JApplet JApplet implementsimplementsimplementsimplements ActionListener {ActionListener {ActionListener {ActionListener {
8 privateprivateprivateprivate String alphabet = String alphabet = String alphabet = String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ""ABCDEFGHIJKLMNOPQRSTUVWXYZ""ABCDEFGHIJKLMNOPQRSTUVWXYZ""ABCDEFGHIJKLMNOPQRSTUVWXYZ";;;;
9 privateprivateprivateprivate finalfinalfinalfinal staticstaticstaticstatic intintintint SIZESIZESIZESIZE = = = = 3333;;;;
10 privateprivateprivateprivate JLabel outputs[];JLabel outputs[];JLabel outputs[];JLabel outputs[];
11 privateprivateprivateprivate JCheckBox checkboxes[]; JCheckBox checkboxes[]; JCheckBox checkboxes[]; JCheckBox checkboxes[];
12 privateprivateprivateprivate Thread threads[];Thread threads[];Thread threads[];Thread threads[];
13 privateprivateprivateprivate booleanbooleanbooleanboolean suspended[];suspended[];suspended[];suspended[];
14
15 // set up GUI and arrays// set up GUI and arrays// set up GUI and arrays// set up GUI and arrays
16 publicpublicpublicpublic voidvoidvoidvoid init()init()init()init()
17 {{{{
18 outputs = outputs = outputs = outputs = newnewnewnew JLabel[ JLabel[ JLabel[ JLabel[ SIZESIZESIZESIZE ];];];];
19 checkboxes = checkboxes = checkboxes = checkboxes = newnewnewnew JCheckBox[ JCheckBox[ JCheckBox[ JCheckBox[ SIZESIZESIZESIZE ];];];];
20 threads = threads = threads = threads = newnewnewnew Thread[ Thread[ Thread[ Thread[ SIZESIZESIZESIZE ];];];];
21 suspended = suspended = suspended = suspended = newnewnewnew booleanbooleanbooleanboolean[ [ [ [ SIZESIZESIZESIZE ];];];];
22
23 Container container = getContentPane();Container container = getContentPane();Container container = getContentPane();Container container = getContentPane();
24 container.setLayout( container.setLayout( container.setLayout( container.setLayout( newnewnewnew GridLayout( GridLayout( GridLayout( GridLayout( SIZESIZESIZESIZE, , , , 2222, , , , 5555, , , , 5555 ) );) );) );) );
25
26 // create GUI components, register listeners and attach // create GUI components, register listeners and attach // create GUI components, register listeners and attach // create GUI components, register listeners and attach
27 // components to content pane// components to content pane// components to content pane// components to content pane
28 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < ; count < ; count < ; count < SIZESIZESIZESIZE; count++ ) {; count++ ) {; count++ ) {; count++ ) {
29 outputs[ count ] = outputs[ count ] = outputs[ count ] = outputs[ count ] = newnewnewnew JLabel();JLabel();JLabel();JLabel();
30 outputs[ count ].setBackground( Color.outputs[ count ].setBackground( Color.outputs[ count ].setBackground( Color.outputs[ count ].setBackground( Color.GREENGREENGREENGREEN ););););
31 outputs[ count ].setOpaque( outputs[ count ].setOpaque( outputs[ count ].setOpaque( outputs[ count ].setOpaque( truetruetruetrue ););););
32 container.add( outputs[ count ] );container.add( outputs[ count ] );container.add( outputs[ count ] );container.add( outputs[ count ] );
33
34 checkboxes[ count ] = checkboxes[ count ] = checkboxes[ count ] = checkboxes[ count ] = newnewnewnew JCheckBox( JCheckBox( JCheckBox( JCheckBox( "Suspended""Suspended""Suspended""Suspended" ););););
35 checkboxes[ count ].addActionListener( checkboxes[ count ].addActionListener( checkboxes[ count ].addActionListener( checkboxes[ count ].addActionListener( thisthisthisthis ););););
36 container.add( checkboxes[ count ] );container.add( checkboxes[ count ] );container.add( checkboxes[ count ] );container.add( checkboxes[ count ] );
37 }}}}
38
39 } } } } // end method init// end method init// end method init// end method init
40
41 // create and start threads each time start is called (i.e., after // create and start threads each time start is called (i.e., after // create and start threads each time start is called (i.e., after // create and start threads each time start is called (i.e., after
42 // init and when user revists Web page containing this applet)// init and when user revists Web page containing this applet)// init and when user revists Web page containing this applet)// init and when user revists Web page containing this applet)
43 publicpublicpublicpublic voidvoidvoidvoid start()start()start()start()
44 {{{{
45 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < threads.length; count++ ) {; count < threads.length; count++ ) {; count < threads.length; count++ ) {; count < threads.length; count++ ) {
46
47 // create Thread; initialize object that implements Runnable// create Thread; initialize object that implements Runnable// create Thread; initialize object that implements Runnable// create Thread; initialize object that implements Runnable
48 threads[ count ] = threads[ count ] = threads[ count ] = threads[ count ] =
49 newnewnewnew Thread( Thread( Thread( Thread( newnewnewnew RunnableObject(), RunnableObject(), RunnableObject(), RunnableObject(), "Thread ""Thread ""Thread ""Thread " + ( count + + ( count + + ( count + + ( count + 1111 ) );) );) );) );
50
51 threads[ count ].start(); threads[ count ].start(); threads[ count ].start(); threads[ count ].start(); // begin executing Thread// begin executing Thread// begin executing Thread// begin executing Thread
52 }}}}
Applet start method
Create three Thread objects and initialize each with a
RunnableObject
Call thread start method
53 }}}}
54
55 // determine thread location in threads array// determine thread location in threads array// determine thread location in threads array// determine thread location in threads array
56 privateprivateprivateprivate intintintint getIndex( Thread current )getIndex( Thread current )getIndex( Thread current )getIndex( Thread current )
57 {{{{
58 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < threads.length; count++ ); count < threads.length; count++ ); count < threads.length; count++ ); count < threads.length; count++ )
59 ifififif ( current == threads[ count ] )( current == threads[ count ] )( current == threads[ count ] )( current == threads[ count ] )
60 returnreturnreturnreturn count;count;count;count;
61
62 returnreturnreturnreturn ----1111; ; ; ;
63 }}}}
64
65 // called when user switches Web pages; stops all threads// called when user switches Web pages; stops all threads// called when user switches Web pages; stops all threads// called when user switches Web pages; stops all threads
66 publicpublicpublicpublic synchronizedsynchronizedsynchronizedsynchronized voidvoidvoidvoid stop()stop()stop()stop()
67 {{{{
68 // set references to null to terminate each thread's run method// set references to null to terminate each thread's run method// set references to null to terminate each thread's run method// set references to null to terminate each thread's run method
69 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < threads.length; count++ ) ; count < threads.length; count++ ) ; count < threads.length; count++ ) ; count < threads.length; count++ )
70 threads[ count ] = threads[ count ] = threads[ count ] = threads[ count ] = nullnullnullnull;;;;
71
72 notifyAll(); notifyAll(); notifyAll(); notifyAll(); // notify all waiting threads, so they can terminate// notify all waiting threads, so they can terminate// notify all waiting threads, so they can terminate// notify all waiting threads, so they can terminate
73 }}}}
74
75 // handle button events// handle button events// handle button events// handle button events
76 publicpublicpublicpublic synchronizedsynchronizedsynchronizedsynchronized voidvoidvoidvoid actionPerformed( ActionEvent event )actionPerformed( ActionEvent event )actionPerformed( ActionEvent event )actionPerformed( ActionEvent event )
77 {{{{
Method stop stops all threads
Set thread references in array threads to
nullInvoke method
notifyAll to ready waiting threads
78 forforforfor ( ( ( ( intintintint count = count = count = count = 0000; count < checkboxes.length; count++ ) {; count < checkboxes.length; count++ ) {; count < checkboxes.length; count++ ) {; count < checkboxes.length; count++ ) {
79
80 ifififif ( event.getSource() == checkboxes[ count ] ) {( event.getSource() == checkboxes[ count ] ) {( event.getSource() == checkboxes[ count ] ) {( event.getSource() == checkboxes[ count ] ) {
81 suspended[ count ] = !suspended[ count ];suspended[ count ] = !suspended[ count ];suspended[ count ] = !suspended[ count ];suspended[ count ] = !suspended[ count ];
82
83 // change label color on suspend/resume// change label color on suspend/resume// change label color on suspend/resume// change label color on suspend/resume
84 outputs[ count ].setBackground(outputs[ count ].setBackground(outputs[ count ].setBackground(outputs[ count ].setBackground(
85 suspended[ count ] ? Color.suspended[ count ] ? Color.suspended[ count ] ? Color.suspended[ count ] ? Color.REDREDREDRED : Color.: Color.: Color.: Color.GREENGREENGREENGREEN ););););
86
87 // if thread resumed, make sure it starts executing// if thread resumed, make sure it starts executing// if thread resumed, make sure it starts executing// if thread resumed, make sure it starts executing
88 ifififif ( !suspended[ count ] )( !suspended[ count ] )( !suspended[ count ] )( !suspended[ count ] )
89 notifyAll(); notifyAll(); notifyAll(); notifyAll();
90
91 returnreturnreturnreturn;;;;
92 }}}}
93 }}}}
94
95 } } } } // end method actionPerformed// end method actionPerformed// end method actionPerformed// end method actionPerformed
96
97 // private inner class that implements Runnable to control threads// private inner class that implements Runnable to control threads// private inner class that implements Runnable to control threads// private inner class that implements Runnable to control threads
98 privateprivateprivateprivate classclassclassclass RunnableObject RunnableObject RunnableObject RunnableObject implementsimplementsimplementsimplements Runnable {Runnable {Runnable {Runnable {
99
100 // place random characters in GUI, variables currentThread and // place random characters in GUI, variables currentThread and // place random characters in GUI, variables currentThread and // place random characters in GUI, variables currentThread and
101 // index are final so can be used in an anonymous inner class// index are final so can be used in an anonymous inner class// index are final so can be used in an anonymous inner class// index are final so can be used in an anonymous inner class
102 publicpublicpublicpublic voidvoidvoidvoid run()run()run()run()
103 {{{{
Toggle booleanvalue in array suspended
Call notifyAll to start ready threads
Class RunnableObjectimplements Runnable
interface
Declare method run
104 // get reference to executing thread// get reference to executing thread// get reference to executing thread// get reference to executing thread
105 finalfinalfinalfinal Thread currentThread = Thread.currentThread();Thread currentThread = Thread.currentThread();Thread currentThread = Thread.currentThread();Thread currentThread = Thread.currentThread();
106
107 // determine thread's position in array// determine thread's position in array// determine thread's position in array// determine thread's position in array
108 finalfinalfinalfinal intintintint index = getIndex( currentThread );index = getIndex( currentThread );index = getIndex( currentThread );index = getIndex( currentThread );
109
110 // loop condition determines when thread should stop; loop // loop condition determines when thread should stop; loop // loop condition determines when thread should stop; loop // loop condition determines when thread should stop; loop
111 // terminates when reference threads[ index ] becomes null// terminates when reference threads[ index ] becomes null// terminates when reference threads[ index ] becomes null// terminates when reference threads[ index ] becomes null
112 whilewhilewhilewhile ( threads[ index ] == currentThread ) {( threads[ index ] == currentThread ) {( threads[ index ] == currentThread ) {( threads[ index ] == currentThread ) {
113
114 // sleep from 0 to 1 second// sleep from 0 to 1 second// sleep from 0 to 1 second// sleep from 0 to 1 second
115 trytrytrytry {{{{
116 Thread.sleep( ( Thread.sleep( ( Thread.sleep( ( Thread.sleep( ( intintintint ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * 1000100010001000 ) );) );) );) );
117
118 // determine whether thread should suspend execution;// determine whether thread should suspend execution;// determine whether thread should suspend execution;// determine whether thread should suspend execution;
119 // synchronize on RandomCharacters applet object// synchronize on RandomCharacters applet object// synchronize on RandomCharacters applet object// synchronize on RandomCharacters applet object
120 synchronizedsynchronizedsynchronizedsynchronized( RandomCharacters.( RandomCharacters.( RandomCharacters.( RandomCharacters.thisthisthisthis ) { ) { ) { ) {
121
122 whilewhilewhilewhile ( suspended[ index ] && ( suspended[ index ] && ( suspended[ index ] && ( suspended[ index ] &&
123 threads[ index ] == currentThread ) { threads[ index ] == currentThread ) { threads[ index ] == currentThread ) { threads[ index ] == currentThread ) {
124
125 // temporarily suspend thread execution// temporarily suspend thread execution// temporarily suspend thread execution// temporarily suspend thread execution
126 RandomCharacters.RandomCharacters.RandomCharacters.RandomCharacters.thisthisthisthis.wait(); .wait(); .wait(); .wait();
127 } } } }
128 } } } } // end synchronized statement // end synchronized statement // end synchronized statement // end synchronized statement
The while loop executes as long as the index of array
threads equals currentThread
The synchronizedblock helps suspend currently executing
thread
Invoke method waiton applet to place thread in waiting
state
40
129
130 } } } } // end try// end try// end try// end try
131
132 // if thread interrupted during wait/sleep, print stack trace// if thread interrupted during wait/sleep, print stack trace// if thread interrupted during wait/sleep, print stack trace// if thread interrupted during wait/sleep, print stack trace
133 catchcatchcatchcatch ( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {( InterruptedException exception ) {
134 exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();exception.printStackTrace();
135 }}}}
136
137 // display character on corresponding JLabel// display character on corresponding JLabel// display character on corresponding JLabel// display character on corresponding JLabel
138 SwingUtilities.invokeLater( SwingUtilities.invokeLater( SwingUtilities.invokeLater( SwingUtilities.invokeLater(
139 newnewnewnew Runnable() {Runnable() {Runnable() {Runnable() {
140
141 // pick random character and display it// pick random character and display it// pick random character and display it// pick random character and display it
142 publicpublicpublicpublic voidvoidvoidvoid run() run() run() run()
143 {{{{
144 charcharcharchar displayChar = displayChar = displayChar = displayChar =
145 alphabet.charAt( ( alphabet.charAt( ( alphabet.charAt( ( alphabet.charAt( ( intintintint ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * ) ( Math.random() * 26262626 ) );) );) );) );
146
147 outputs[ index ].setText( outputs[ index ].setText( outputs[ index ].setText( outputs[ index ].setText(
148 currentThread.getName() + currentThread.getName() + currentThread.getName() + currentThread.getName() + ": "": "": "": " + displayChar );+ displayChar );+ displayChar );+ displayChar );
149 }}}}
150
151 } } } } // end inner class// end inner class// end inner class// end inner class
152
153 ); ); ); ); // end call to SwingUtilities.invokeLater// end call to SwingUtilities.invokeLater// end call to SwingUtilities.invokeLater// end call to SwingUtilities.invokeLater
Anonymous inner class implements
Runnable interface