Tópicos Em Java

Hoje, vamos discutir Java Threads com exemplos , visando satisfazer a sede de conhecimento do leitor.

Tópicos Java

Utilizando Java Threads , os threads possibilitam a execução de vários processos simultaneamente, aumentando a eficiência de um programa.

Tarefas complexas podem ser executadas em segundo plano sem interferir no programa principal usando threads.



Criar thread Java

Para criar um thread em Java , existem dois métodos.

Ao lidar com Java Threads , ele é criado substituindo o método run() da classe Thread:

Sintaxe para estender:

public class Main extends Thread {

    public void run(){
        System.out.println("We are learning about Java Threads");
    }
}

A interface Runnable também pode ser usada para criar um thread:

Sintaxe para Implementar

public class Main implements Runnable {
    public void run(){
        System.out.println("A Java Threads can also be created by implementing the runable interface");
    }
}


Executar threads Java

Java Threads oferece suporte a threads em execução criando instâncias de classes que estendem a classe Thread e chamando seu método start() .

Extend Example:1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main extends Thread {
public static void main(String[] args) {
Main my_thread = new Main();
my_thread.start();
System.out.println("The code outside the thread will be executed from here");
}
public void run() {
System.out.println("The following code is a part of thread");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Exemplo de tópicos Java

Extend Example:2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Main extends Thread {
public static void main(String[] args) {
Main mrx_thread = new Main();
System.out.println("This contains the programme code");
mrx_thread.start(); // The arrangement does not matter as both thread and programme code runs side by side to each other
}
public void run() {
System.out.println("This part is associated with a thread in order to run multiple commands at a time using the start method");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Supondo que a classe implemente a interface Runnable , o threadread pode ser executado passando a instância da classe para o construtor do objeto Thread e, em seguida, chamando o método start() do objeto thread:

Implement Example:1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main implements Runnable {
public static void main(String[] args) {
Main mrx = new Main(); // Here we create an object of the Main class
Thread ample_thread = new Thread(mrx); // The instance of ample_thread is created with the object of the Main class
ample_thread.start(); // This calls the thread method
System.out.println("The code in this section is outside the thread");
}
public void run() {
System.out.println("This code lies inside a thread");
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Implement Example:2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Main implements Runnable {
public static void main(String[] args) {
Main mrx = new Main(); // Here we create an object of the Main class
Thread ample_thread = new Thread(mrx); // The instance of ample_thread is created with the object of the Main class
ample_thread.start(); // This calls the thread method
System.out.println("The code for the addition of two integers is written inside the Main Method: "+(10+20));
}
public void run() {
System.out.println("Multiplication is done in a thread of the same numbers: "+(10*20));
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

 

Uma diferença notável é que se uma classe estende a classe Thread, ela não pode estender mais nada, mas se implementa a interface Runnable, também pode estender de outras classes, como:


Problema de simultaneidade

Não há como determinar em que ordem o código será executado porque os threads são executados simultaneamente com outras partes do programa.

Os valores das variáveis ​​são imprevisíveis quando as threads e o programa principal leem e escrevem as mesmas variáveis ​​ao mesmo tempo. Os conflitos resultantes disso são chamados de problemas de simultaneidade .

Aqui está um exemplo de código, onde a variável mrx tem um valor imprevisível:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Main extends Thread {
public static int mrx= 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println(mrx); // Show output as 0
mrx++; // The value of mrx becomes 1
System.out.println(mrx); // Prints 2
}
public void run() {
mrx++; // value of mrx becomes 2 here
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O exemplo dado ilustra a diferença no valor da variável ample ao atribuir o operador de decremento e o operador de incremento a ela:

Example: 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Main extends Thread {
public static int ample= 10;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
System.out.println(ample); // Show output as 10
ample–; // The value of ample becomes 9
System.out.println(ample); // Prints 2
}
public void run() {
ample++; // value of ample becomes 10 again
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

O número de atributos compartilhados entre threads deve ser mantido o mais baixo possível para evitar problemas de simultaneidade.

O método isAlive() do encadeamento pode ser usado para determinar se o encadeamento terminou a execução antes de usar quaisquer atributos que ele possa modificar.

Esta pode ser uma solução se os atributos precisarem ser compartilhados entre as threads.

Problemas de simultaneidade podem ser evitados usando o método isAlive() :

isAlive() Example:1 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Main extends Thread {
public static int mrx= 0;
public static void main(String[] args) {
Main mrx_thread = new Main();
mrx_thread.start();
while (mrx_thread.isAlive()){
System.out.println("Waiting for the thread to complete the code execution");
}
System.out.println(mrx); // Show output as 1 as the thread is utilized first
mrx++; // The value of mrx becomes 2
System.out.println(mrx); // Prints 2 as the value is modified from 1 to 2
}
public void run() {
mrx++; // value of mrx becomes 1 here as thread runs first
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

isAlive Example:2 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Main extends Thread {
public static int ample= 10;
public static void main(String[] args) {
Main mrx_thread = new Main();
mrx_thread.start();
while (mrx_thread.isAlive()){
System.out.println("Waiting for thread to execute first");
}
System.out.println("Thread's value of ample: "+ample); // Show output as 11 as the run() method has incremented the value of ample
ample–; // 1 is subtracted from the threads value
System.out.println("Main Method value: "+ample); // Prints 10 as the value is decreased from 11 to 10
}
public void run() {
ample++; // value of ample is incremented to 11 here
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Benefícios do Java Threads

Consumo eficiente de memória:

Todos os threads dentro de um processo compartilham o mesmo espaço de endereço. Portanto, eles não usam memória compartilhada e várias linhas de código podem ser executadas sem consumir memória adicional.

Melhor utilização de sistemas multiprocessadores:

O uso de encadeamentos permite que um computador/laptop utilize sua arquitetura de multiprocessador em uma extensão mais ampla, pois vários processadores são permitidos na execução de vários códigos de encadeamento por vez.

Nós valorizamos o seu feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Assine a nossa newsletter
Digite seu e-mail para receber um resumo semanal de nossos melhores posts. Saber mais!
ícone