首页 > 编程语言 >Java: Threads

Java: Threads

时间:2022-11-27 23:14:05浏览次数:42  
标签:... Java thread Waiting Threads run Main public

Threads allows a program to operate more efficiently by doing multiple things at the same time.

Creating a Thread

There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run() method:

public class Main extends Thread {
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

Another way to create a thread is to implement the Runnable interface:

public class Main implements Runnable {
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

Running Threads

If the class extends the Thread class, the thread can be run by creating an instance of the class and call its start() method:

public class Main extends Thread {
  public static void main(String[] args) {
    Main thread = new Main();
    thread.start(); -> run()
    System.out.println("This code is outside of the thread");
  }
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

If the class implements the Runnable interface, the thread can be run by passing an instance of the class to a Thread object's constructor and then calling the thread's start() method:

public class Main implements Runnable {
  public static void main(String[] args) {
    Main obj = new Main();
    Thread thread = new Thread(obj);
    thread.start(); -> run()
    System.out.println("This code is outside of the thread");
  }
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

Concurrency Problems

Because threads run at the same time as other parts of the program, there is no way to know in which order the code will run. When the threads and main program are reading and writing the same variables, the values are unpredictable. The problems that result from this are called concurrency problems.

To avoid concurrency problems, it is best to share as few attributes between threads as possible. If attributes need to be shared, one possible solution is to use the isAlive() method of the thread to check whether the thread has finished running before using any attributes that the thread can change.

public class Main extends Thread {
  public static int amount = 0;

  public static void main(String[] args) {
    Main thread = new Main();
    thread.start(); -> run()
    // Wait for the thread to finish
    while(thread.isAlive()) {
      System.out.println("Waiting...");
    }
    // Update amount and print its value
    System.out.println("Main: " + amount);
    amount++;
    System.out.println("Main: " + amount);
  }
  public void run() {
    amount++;
  }
}

// Outputs:
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Waiting...
Main: 1
Main: 2

 

标签:...,Java,thread,Waiting,Threads,run,Main,public
From: https://www.cnblogs.com/ShengLiu/p/16930953.html

相关文章

  • Java: Regular Expressions
    Pattern Class-Definesapattern(tobeusedinasearch)Matcher Class-UsedtosearchforthepatternPatternSyntaxException Class-Indicatessyntaxe......
  • Java中使用正则表达式
    1、使用 java.util.regex.Pattern类的 compole(表达式)方法把正则表达式变成一个对象。//表达式对象:1个数字和1个字母连续Patternpattern=P......
  • Java入门代码练习
    一、第一个Java程序1、helloworldpublicclassHello{publicstaticvoidmain(String[]args){System.out.println("Helloworld!");}}2、变量i......
  • Java Excel导出动态自定义单元格样式
    根据表格内容定义单元格样式效果图:文章描述两种,一种创建生成时定义样式,另一种在excel在写入文件前修改样式关键代码一/***数据动态设置样式*......
  • 用Java打印一个9层空心菱形
    publicclassRhombus{publicstaticvoidmain(Stringargs[]){      for(inti=1;i<=5;i++){  //i表示层数      //空格个数    ......
  • Java: Exceptions - Try...Catch
    tryandcatch  Usetryandcatch:publicclassMain{publicstaticvoidmain(String[]args){try{int[]myNumbers={1,2,3};Syst......
  • Java: Wrapper Classes
    Wrapperclassesprovideawaytouseprimitivedatatypes(int, boolean,etc..)asobjects.PrimitiveDataTypeWrapperClassbyteByteshortShortint......
  • Java: Iterator
    An Iterator isanobjectthatcanbeusedtoloopthroughcollections,like ArrayList and HashSet.//ImporttheArrayListclassandtheIteratorclassi......
  • 线程总述(Java版)
    一、线程创建1、继承Thread类首先,自定义线程类继承THread类;其次,重写run方法,编写线程执行体;最后,创建线程对象并调用start()方法启动线程。但值得注意的是,线程并不一定......
  • 自用_Minecraft Java Server配置、指令等等提示
    尚未写完gamemode=(模式)//adventure冒险模式、creative创造模式、survival生存模式、spectator旁观者模式。online-mode=//用于验证玩家是否“在线”,也就是是否是正版......