Home  >  Article  >  Java  >  Java—detailed examples of processes and threads

Java—detailed examples of processes and threads

PHP中文网
PHP中文网Original
2017-06-21 17:04:202048browse
  • Process and Thread

A process is the execution process of a program (task) and is dynamic; it holds resources (shared memory, shared files) and threads , is the carrier of resources and threads.

Thread is the smallest execution unit in the system. There are multiple threads in the same process, and threads share the resources of the process.

Thread interaction includes mutual exclusion and synchronization.

  • Common methods of threads

Java’s support for threads is mainly reflected in the class Thread and the interface Runnable, both of which inherit the java.lang package. There is a common method run()

  • Thread stop error method: stop(), interrupt()

  • The correct way to stop a thread

public class ArmyRunnable implements Runnable {//volatile保证了线程可以正确读取其他线程写入的值volatile boolean keepRunning = true;
    @Overridepublic void run() {while(keepRunning) {//发动五连击for (int i = 0; i < 5 ; i++) {
                System.out.println(Thread.currentThread().getName() + "进攻对方[" + i + "]");
            }//暂停            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + "结束了战斗");
    }
}
  • Race condition

When When multiple threads share access to the same data (memory area) at the same time, each thread attempts to operate on the data, causing the data to be corrupted. This phenomenon is called a race condition.

  • Interaction of threads: mutual exclusion and synchronization

Mutual exclusion: At the same time, only one thread can process our key data or critical section to operate.

Implementation of mutual exclusion: sysnchronized (intrinsic lock), sysnchronized is equivalent to adding a lock to the code so that other threads cannot enter this critical area to access our key resources.

Synchronization: It is a communication mechanism between threads. Because certain conditions of one thread are not met, other threads are in a certain waiting state. Later, because the conditions are met, one thread will use some kind of method to wake up other threads.

Implementation of synchronization: wait()/notify()/notifyAll()--Member method of Object object

Wait set is the rest room of the thread

public void transfer(int from, int to, double amount) {//通过synchronized 关键字来实现互斥,synchronized既可以出现在方法之上,也能以块的形式出现在方法体之中//通过对lockObj加锁实现互斥//加锁操作是有开销的,多次加锁操作会降低系统的性能synchronized (lockObj) {//while循环,保证条件不满足时任务都会被条件阻挡,而不是继续竞争CPU资源while (energyBoxes[from] < amount) {try {//条件不满足,将当前线程放入锁对象(lockObj)上的wait set//wait set 是线程的休息室                    lockObj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName());
            energyBoxes[from] -= amount;
            System.out.printf("从%d转移%10.2f单位能量到%d", from, amount, to);
            energyBoxes[to] += amount;
            System.out.printf("能量总和:%10.2f%n",getTotalEnergies());            //唤醒所有在lockObj对象上等待的线程            lockObj.notifyAll();
        }
        
    }
  • The difference between creating threads in the Runnable method and the Thread method

  1. The Runnable method can be avoided The Thread method has defects due to the single inheritance feature of Java

  2. The code of Runnable can be shared by multiple threads (Thread instances), which is suitable for multiple threads to process the same resourceSituation

  • Thread life cycle

 

    ##Ready: After creating the thread object, the thread's start() method is called (at this time, the thread just enters the thread queue, waiting to obtain CPU services, and has the conditions to run, but it does not necessarily have started running).
  1. Run: Once the thread in the ready state obtains the CPU resource, it enters the running state and starts executing the logic in the run() method.
  2. Termination: After the thread's run() method is executed, or the thread calls the stop() method (this method has been out), the thread enters the terminated state.
  3. Blocking: Under certain circumstances, an executing thread temporarily gives up CPU resources for some reason, suspends its own execution, and enters a blocking state, such as The sleep() method was called
    User thread and daemon thread
    User thread: Runs in the foreground and performs specific tasks, such as the main thread of the program and sub-threads connected to the network
  1. Daemon thread: runs in the background and serves other foreground threads. Once all user threads are After finishing the operation, the daemon thread will end its work together with the JVM.
  2. Application of daemon thread: monitoring thread in database connection pool, monitoring thread after JVM virtual machine is started. The most common daemon thread is the garbage collection thread
  3. Set the daemon thread: Set the current thread as a daemon thread by calling the setDaemon(true) method of the Thread class. Note: setDaemon(true) must be called before the start() method, otherwise an exception will be thrown; the new thread generated in the daemon thread is also a daemon thread; not all tasks can be assigned to daemon threads for execution, such as read and write operations. Or computational logic.
    Extension
  • Java Memory Mode

Locks & Condition

Thread Security: Atomicity and visibility...

Commonly used interaction models in multi-threaded programming

Concurrent programming tools in Java5

##Reference book
  •  core java
 Java concurrency in practice

The above is the detailed content of Java—detailed examples of processes and threads. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn