Java thread is an independent execution path through programming code. If we run multiple threads, the path of one thread will be different from the rest. For example, consider that an ordinary thread executes the byte code according to the if part of the if-else statement, meanwhile another thread executes the byte code according to an else part. Here is a question about how JVM (Java Virtual Machine) keeps track of each thread execution. The JVM provides the method called stack to each thread. To keep track of the current bytecode instruction, the stack method keeps track of local variables, the JVM passes to a method, and the method returns a value. In the case where multiple threads execute byte code instructions in the same program, this process is called multithreading. It has some program-specific advantages: Multithreaded GUI (graphical user interface)-based programs are able to respond to users while they perform other tasks. Threaded programs finish virtually faster than their unthreaded counterparts. It typically happens when threads run on a multiprocessor machine where each thread has its own processor. The multithreading process runs in the Java class called java.lang.Thread. Each Thread object acts as a single thread of execution, and that execution is performed in the run() method of the Thread object. It is since the default run() method doesn't actually do anything, we need to create a Thread subclass and override the run() method to get the job done. Synchronization is a process of ordering a thread in time for thread access that allows multiple threads to handle instance and class field variables. These sequences can be called critical code sections. Why is synchronization necessary? For example, we should write... in the middle of a sheet of paper... the same critical section of code. Before the technology did not develop so much, all program threads had their own single-processor machines to execute their code, but at present, as we know, modern computers have numerous processors. Therefore threads often share one or more processors. There is a term called thread scheduling which decides how to share processor resources among program threads. There are 2 specific things about thread scheduling that we need to mention: 1) We need to be careful when writing a Java program whose behavior depends on how threads are scheduled and must run consistently across different platforms, because Java does not force the VM to schedule threads. 2) When we write Java programs, we need to think about how Java schedules threads for a long time. To ensure that the computation thread does not monopolize the processor.
tags