SlideShare a Scribd company logo
69 Curso de Java
Criando várias
Threads +
métodos
isAlive e join
public static void main(String[] args) {
MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300);
MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450);
MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500);
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
Thread t3 = new Thread(thread3);
t1.start();
t2.start();
t3.start();
for (int i=0; i<5; i++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Thread main interrompida");
}
}
System.out.println(".............Thread main terminada");
}
• última linha do programa é impressa na tela antes das
threads terminarem a execução
• como podemos fazer que a última linha do programa
seja a última linha executada?
• isAlive retorna true se aThread ainda estiver sendo
executada, ou seja, não foi terminada
Ciclo de Vida
New Runnable
RunningDead
start()
run()
new Thread()
pronta pra execução
em execução
criação da instância
Waitingyield()
sleep()
wait()
suspend()
quando a thread “acorda”
notify() / notifyAll()
resume()
thread terminada
public static void main(String[] args) {
MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300);
MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450);
MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500);
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
Thread t3 = new Thread(thread3);
t1.start();
t2.start();
t3.start();
do{
System.out.print("*");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Thread main interrompida");
}
}while (t1.isAlive() || t2.isAlive() || t3.isAlive());
System.out.println(".............Thread main terminada");
}
public static void main(String[] args) {
MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300);
MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450);
MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500);
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
Thread t3 = new Thread(thread3);
t1.start();
t2.start();
t3.start();
do{
System.out.print("*");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
System.out.println("Thread main interrompida");
}
}while (t1.isAlive() || t2.isAlive() || t3.isAlive());
System.out.println(".............Thread main terminada");
}
• ainda existe uma outra forma de se fazer isso, que é
usando o método join
• join: espera até que a thread termine a execução
public static void main(String[] args) {
MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300);
MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450);
MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500);
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
Thread t3 = new Thread(thread3);
t1.start();
try { t1.join(200); } catch (InterruptedException e) { e.printStackTrace(); }
//inicia t2 somente depois de 2 segundos ou que t1 termine
t2.start();
try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); }
//inicia t3 somente depois que t1 termine
t3.start();
try{
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
System.out.println("Thread main interrompida");
}
//termina somente depois que as 3 threads terminarem
System.out.println(".............Thread main terminada");
}
public static void main(String[] args) {
MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300);
MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450);
MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500);
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
Thread t3 = new Thread(thread3);
t1.start();
try { t1.join(200); } catch (InterruptedException e) { e.printStackTrace(); }
//inicia t2 somente depois de 2 segundos ou que t1 termine
t2.start();
try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); }
//inicia t3 somente depois que t1 termine
t3.start();
try{
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
System.out.println("Thread main interrompida");
}
//termina somente depois que as 3 threads terminarem
System.out.println(".............Thread main terminada");
}
https://github.com/loiane/curso-java-basico
Código Fonte:
Não conhece Git/Github?
http://www.loiane.com/2013/11/
screencast-git-e-github-para-iniciantes
http://loiane.training
Fórum para dúvidas + certificado do curso.
Cadastro em:
Obrigada!
http://loiane.com
facebook.com/loianegroner
twitter.com/loiane
https://github.com/loiane
youtube.com/loianegroner
http://loiane.training

More Related Content

What's hot

Boostライブラリ一周の旅
Boostライブラリ一周の旅 Boostライブラリ一周の旅
Boostライブラリ一周の旅 Akira Takahashi
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
Chih-Hsuan Kuo
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
Chih-Hsuan Kuo
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
maksym220889
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
Chih-Hsuan Kuo
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
Seok-joon Yun
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring Effects
Shinpei Hayashi
 
Network security
Network securityNetwork security
Network security
Rakesh chaudhary
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
Chih-Hsuan Kuo
 
Threadlifecycle.36
Threadlifecycle.36Threadlifecycle.36
Threadlifecycle.36myrajendra
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
Ghadeer AlHasan
 
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196
Mahmoud Samir Fayed
 
7th lab
7th lab7th lab
7th lab
rajiprateesh
 
Showdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp KrennShowdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp Krenn
JavaDayUA
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196
Mahmoud Samir Fayed
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading
Vitali Pekelis
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2Technopark
 

What's hot (20)

Boostライブラリ一周の旅
Boostライブラリ一周の旅 Boostライブラリ一周の旅
Boostライブラリ一周の旅
 
Use C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in GeckoUse C++ to Manipulate mozSettings in Gecko
Use C++ to Manipulate mozSettings in Gecko
 
Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36Effective Modern C++ - Item 35 & 36
Effective Modern C++ - Item 35 & 36
 
14 thread
14 thread14 thread
14 thread
 
Java concurrency - Thread pools
Java concurrency - Thread poolsJava concurrency - Thread pools
Java concurrency - Thread pools
 
Ownership System in Rust
Ownership System in RustOwnership System in Rust
Ownership System in Rust
 
Threads
ThreadsThreads
Threads
 
Modern C++ Concurrency API
Modern C++ Concurrency APIModern C++ Concurrency API
Modern C++ Concurrency API
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring Effects
 
Network security
Network securityNetwork security
Network security
 
Protocol handler in Gecko
Protocol handler in GeckoProtocol handler in Gecko
Protocol handler in Gecko
 
Threadlifecycle.36
Threadlifecycle.36Threadlifecycle.36
Threadlifecycle.36
 
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
 
#5 (Remote Method Invocation)
#5 (Remote Method Invocation)#5 (Remote Method Invocation)
#5 (Remote Method Invocation)
 
The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196The Ring programming language version 1.7 book - Part 52 of 196
The Ring programming language version 1.7 book - Part 52 of 196
 
7th lab
7th lab7th lab
7th lab
 
Showdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp KrennShowdown of the Asserts by Philipp Krenn
Showdown of the Asserts by Philipp Krenn
 
The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196The Ring programming language version 1.7 book - Part 84 of 196
The Ring programming language version 1.7 book - Part 84 of 196
 
Advanced #3 threading
Advanced #3  threading Advanced #3  threading
Advanced #3 threading
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 

Viewers also liked

[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import
[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import
[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import
Loiane Groner
 
Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)
Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)
Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)
Loiane Groner
 
[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws
[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws
[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws
Loiane Groner
 
[Curso Java Basico] Aula 73: Threads: resume, suspend e stop
[Curso Java Basico] Aula 73: Threads: resume, suspend e stop[Curso Java Basico] Aula 73: Threads: resume, suspend e stop
[Curso Java Basico] Aula 73: Threads: resume, suspend e stop
Loiane Groner
 
[Curso Java Basico] Aula 22: Como debugar no Eclipse
[Curso Java Basico] Aula 22: Como debugar no Eclipse[Curso Java Basico] Aula 22: Como debugar no Eclipse
[Curso Java Basico] Aula 22: Como debugar no Eclipse
Loiane Groner
 
[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...
[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...
[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...
Loiane Groner
 
Curso Java Basico] Aula 67: Criando Threads + metodos start, run e sleep
Curso Java Basico] Aula 67: Criando Threads + metodos start, run e sleepCurso Java Basico] Aula 67: Criando Threads + metodos start, run e sleep
Curso Java Basico] Aula 67: Criando Threads + metodos start, run e sleep
Loiane Groner
 
[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...
[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...
[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...
Loiane Groner
 
[Curso Java Basico - Exceptions] Aula 47: try, catch
[Curso Java Basico - Exceptions] Aula 47: try, catch[Curso Java Basico - Exceptions] Aula 47: try, catch
[Curso Java Basico - Exceptions] Aula 47: try, catch
Loiane Groner
 
[Curso Java Basico] Aula 55: Enum: metodos value e valueOf
[Curso Java Basico] Aula 55: Enum: metodos value e valueOf[Curso Java Basico] Aula 55: Enum: metodos value e valueOf
[Curso Java Basico] Aula 55: Enum: metodos value e valueOf
Loiane Groner
 
[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)
[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)
[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)
Loiane Groner
 
[Curso Java Basico] Aula 68: Threads: Interface Runnable
[Curso Java Basico] Aula 68: Threads: Interface Runnable[Curso Java Basico] Aula 68: Threads: Interface Runnable
[Curso Java Basico] Aula 68: Threads: Interface Runnable
Loiane Groner
 
[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...
[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...
[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...
Loiane Groner
 
[Curso Java Basico] Aula 65: Annotations (anotacoes)
[Curso Java Basico] Aula 65: Annotations (anotacoes)[Curso Java Basico] Aula 65: Annotations (anotacoes)
[Curso Java Basico] Aula 65: Annotations (anotacoes)
Loiane Groner
 
[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll
[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll
[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll
Loiane Groner
 
[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super
[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super
[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super
Loiane Groner
 
[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...
[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...
[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...
Loiane Groner
 
[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...
[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...
[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...
Loiane Groner
 
[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)
Loiane Groner
 
[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples
[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples
[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples
Loiane Groner
 

Viewers also liked (20)

[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import
[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import
[Curso Java Basico - Orientacao a Objetos] Aula 28: Pacotes (packages) e import
 
Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)
Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)
Curso Java Basico] Aula 66: Garbage Collector (Coletor de Lixo)
 
[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws
[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws
[Curso Java Basico - Exceptions] Aula 50: stacktrace e throws
 
[Curso Java Basico] Aula 73: Threads: resume, suspend e stop
[Curso Java Basico] Aula 73: Threads: resume, suspend e stop[Curso Java Basico] Aula 73: Threads: resume, suspend e stop
[Curso Java Basico] Aula 73: Threads: resume, suspend e stop
 
[Curso Java Basico] Aula 22: Como debugar no Eclipse
[Curso Java Basico] Aula 22: Como debugar no Eclipse[Curso Java Basico] Aula 22: Como debugar no Eclipse
[Curso Java Basico] Aula 22: Como debugar no Eclipse
 
[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...
[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...
[Curso Java Basico - Orientacao a Objetos] Aula 31: Modificadores private e p...
 
Curso Java Basico] Aula 67: Criando Threads + metodos start, run e sleep
Curso Java Basico] Aula 67: Criando Threads + metodos start, run e sleepCurso Java Basico] Aula 67: Criando Threads + metodos start, run e sleep
Curso Java Basico] Aula 67: Criando Threads + metodos start, run e sleep
 
[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...
[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...
[Curso Java Basico - Orientacao a Objetos] Aula 34: Variáveis e metodos estat...
 
[Curso Java Basico - Exceptions] Aula 47: try, catch
[Curso Java Basico - Exceptions] Aula 47: try, catch[Curso Java Basico - Exceptions] Aula 47: try, catch
[Curso Java Basico - Exceptions] Aula 47: try, catch
 
[Curso Java Basico] Aula 55: Enum: metodos value e valueOf
[Curso Java Basico] Aula 55: Enum: metodos value e valueOf[Curso Java Basico] Aula 55: Enum: metodos value e valueOf
[Curso Java Basico] Aula 55: Enum: metodos value e valueOf
 
[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)
[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)
[Curso Java Basico] Aula 54: Enumeradores como classe (construtor e metodos)
 
[Curso Java Basico] Aula 68: Threads: Interface Runnable
[Curso Java Basico] Aula 68: Threads: Interface Runnable[Curso Java Basico] Aula 68: Threads: Interface Runnable
[Curso Java Basico] Aula 68: Threads: Interface Runnable
 
[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...
[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...
[Curso Java Basico - Orientacao a Objetos] Aula 32: Encapsulamento: métodos g...
 
[Curso Java Basico] Aula 65: Annotations (anotacoes)
[Curso Java Basico] Aula 65: Annotations (anotacoes)[Curso Java Basico] Aula 65: Annotations (anotacoes)
[Curso Java Basico] Aula 65: Annotations (anotacoes)
 
[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll
[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll
[Curso Java Basico] Aula 72: Threads: notify, wait e notifyAll
 
[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super
[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super
[Curso Java Basico - Orientacao a Objetos] Aula 38: Herança: Palavra chave super
 
[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...
[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...
[Curso Java Basico - Orientacao a Objetos] Aula 33: Sobrecarga de metodos e c...
 
[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...
[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...
[Curso Java Basico] Aula 71: Threads: metodos e blocos sincronizados (synchro...
 
[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)[Curso Java Basico] Aula 59: Importacao estatica (static import)
[Curso Java Basico] Aula 59: Importacao estatica (static import)
 
[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples
[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples
[Curso Java Basico - Orientacao a Objetos] Aula 25: Classes e metodos simples
 

Similar to [Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join

Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
RanjithaM32
 
Thread 1
Thread 1Thread 1
Thread 1
RAVI MAURYA
 
Thread priorities
Thread prioritiesThread priorities
Thread priorities
Then Murugeshwari
 
Threads in java
Threads in javaThreads in java
Threads in java
mukesh singh
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
ishan0019
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
Arulmozhivarman8
 
Tutorial4 Threads
Tutorial4  ThreadsTutorial4  Threads
Tutorial4 Threadstech2click
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
Mahmoud Ouf
 
multithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.pptmultithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.ppt
shikhaverma566116
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
TabassumMaktum
 
Threads
ThreadsThreads
Threads
RanjithaM32
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
Platonov Sergey
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
PragatiSutar4
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
java-thread
java-threadjava-thread
java-thread
babu4b4u
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 

Similar to [Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join (20)

Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Thread 1
Thread 1Thread 1
Thread 1
 
Thread priorities
Thread prioritiesThread priorities
Thread priorities
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 
Threading
ThreadingThreading
Threading
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
Tutorial4 Threads
Tutorial4  ThreadsTutorial4  Threads
Tutorial4 Threads
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
multithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.pptmultithreading, creating a thread and life cycle in java.ppt
multithreading, creating a thread and life cycle in java.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Threads
ThreadsThreads
Threads
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
java-thread
java-threadjava-thread
java-thread
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 

Recently uploaded

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 

Recently uploaded (20)

Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 

[Curso Java Basico] Aula 69: Criando varias Threads + metodos isAlive e join

  • 1. 69 Curso de Java Criando várias Threads + métodos isAlive e join
  • 2. public static void main(String[] args) { MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300); MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450); MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500); Thread t1 = new Thread(thread1); Thread t2 = new Thread(thread2); Thread t3 = new Thread(thread3); t1.start(); t2.start(); t3.start(); for (int i=0; i<5; i++){ try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("Thread main interrompida"); } } System.out.println(".............Thread main terminada"); }
  • 3. • última linha do programa é impressa na tela antes das threads terminarem a execução • como podemos fazer que a última linha do programa seja a última linha executada?
  • 4. • isAlive retorna true se aThread ainda estiver sendo executada, ou seja, não foi terminada
  • 5. Ciclo de Vida New Runnable RunningDead start() run() new Thread() pronta pra execução em execução criação da instância Waitingyield() sleep() wait() suspend() quando a thread “acorda” notify() / notifyAll() resume() thread terminada
  • 6. public static void main(String[] args) { MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300); MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450); MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500); Thread t1 = new Thread(thread1); Thread t2 = new Thread(thread2); Thread t3 = new Thread(thread3); t1.start(); t2.start(); t3.start(); do{ System.out.print("*"); try { Thread.sleep(200); } catch (InterruptedException e) { System.out.println("Thread main interrompida"); } }while (t1.isAlive() || t2.isAlive() || t3.isAlive()); System.out.println(".............Thread main terminada"); }
  • 7. public static void main(String[] args) { MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300); MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450); MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500); Thread t1 = new Thread(thread1); Thread t2 = new Thread(thread2); Thread t3 = new Thread(thread3); t1.start(); t2.start(); t3.start(); do{ System.out.print("*"); try { Thread.sleep(200); } catch (InterruptedException e) { System.out.println("Thread main interrompida"); } }while (t1.isAlive() || t2.isAlive() || t3.isAlive()); System.out.println(".............Thread main terminada"); }
  • 8. • ainda existe uma outra forma de se fazer isso, que é usando o método join • join: espera até que a thread termine a execução
  • 9. public static void main(String[] args) { MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300); MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450); MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500); Thread t1 = new Thread(thread1); Thread t2 = new Thread(thread2); Thread t3 = new Thread(thread3); t1.start(); try { t1.join(200); } catch (InterruptedException e) { e.printStackTrace(); } //inicia t2 somente depois de 2 segundos ou que t1 termine t2.start(); try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } //inicia t3 somente depois que t1 termine t3.start(); try{ t1.join(); t2.join(); t3.join(); } catch (InterruptedException e) { System.out.println("Thread main interrompida"); } //termina somente depois que as 3 threads terminarem System.out.println(".............Thread main terminada"); }
  • 10. public static void main(String[] args) { MinhaThreadRunnable thread1 = new MinhaThreadRunnable("#1", 300); MinhaThreadRunnable thread2 = new MinhaThreadRunnable("#2", 450); MinhaThreadRunnable thread3 = new MinhaThreadRunnable("#3", 500); Thread t1 = new Thread(thread1); Thread t2 = new Thread(thread2); Thread t3 = new Thread(thread3); t1.start(); try { t1.join(200); } catch (InterruptedException e) { e.printStackTrace(); } //inicia t2 somente depois de 2 segundos ou que t1 termine t2.start(); try { t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } //inicia t3 somente depois que t1 termine t3.start(); try{ t1.join(); t2.join(); t3.join(); } catch (InterruptedException e) { System.out.println("Thread main interrompida"); } //termina somente depois que as 3 threads terminarem System.out.println(".............Thread main terminada"); }
  • 13. http://loiane.training Fórum para dúvidas + certificado do curso. Cadastro em: