"Java concurrent threads of the United States' first chapter of concurrent programming thread basis

1. wait () function

1.1 blocked thread

Thread calls the shared variable wait (), this calling thread will be blocked pending,

Until the following occurs:

  • . A call the other thread shared object notify () or notifyAll ();
  • b. Other thread calls interrupt the thread (), the thread throws InterruptedException exception return

1.2 monitor lock shared variables

Call shared variable wait () method when the election yo get to ride the monitor lock

How to get the monitor lock?

  1. Sync block; the synchronized (shared variables) {}
  2. The synchronization method; synchronized void method (int a, int b) {}
  • wait()
  • wait (long timeout) Timeout
  • wait(long timeout, int nanos)

Demo02

2. notify () function

  • notify()
  • notifyAll()

  • When a thread calls the shared object notify (), you will wake up with a hang wait series method on the shared variable thread
  • Wake random multiple threads

  • notifyAll (), evoke all

Demo03.java

3. join()

Waiting thread execution method of termination

(After waiting a few things to complete before continuing down the implementation,
such as multi-threaded load resources necessary to wait for multiple threads fully loaded then aggregated processing)
Demo04_join.java

4. sleep()

public static native void sleep(long millis) throws InterruptedException;
public static void sleep(long millis, int nanos) throws InterruptedException;

The calling thread will temporarily give up the right to perform the specified time, the CPU is not involved in scheduling,
but the thread has all the monitor resources, such as locks held let out.

Demo05_Sleep.java

When a thread is in a sleep state, another thread interrupts it, then () call at thrown in sleep
Demo05_SleepInterruptedException.java

5. public static native void yield();

yiled yield; production, produce; give up; to surrender;

Let the executive power CPU.


一般会很少用这个方法, 在调试或者测试时使用或许可以帮助复现由于并发竞争条件导致的问题

* sleep与yield区别

| sleep | yield | 
| --- | --- |
|阻塞线程(挂起指定时间) | 不被阻塞挂起, 线程让出剩余时间片, 处于就绪状态 |
|期间线程调度器不会取调用线程 | 线程调度器下一次调度可能会调用当前线程执行 |

## 6. 线程中断
设置线程中断标志, 不能直接终止线程, 而是被中断线程根据中断状态自行处理

| method | function | description | 
| --- | --- |
|void interrupt()        | 中断线程 | 别的线程调用本线程的interrupt(), 仅仅设置标志, 并不会中断线程; 如果调用时本线程被阻塞挂(wait,join,sleep), 则会抛出InterruptedExceptiony异常(标记就会失败) |
|boolean isInterrupted() | 检测当前线程是否被中断 | 是则返回true  |
|boolean interrupted()   | 检测当前线程是否被中断 | 是则返回true, 并清除中断标志 |

**需要注意的是: interrupted() 是静态方法, 而且内部是操作当前线程, 而非操作 调用interrupted()的实例对象的中断标志**
public static boolean interrupted() {
    return currentThread().isInterrupted(true);
}

Demo07_DetermineIfTheThreadIsTerminatedByInterruptFlag.java```

Demo07_IsInterruptedAndInterrupted.java

7. appreciated thread context switching

CPU can only use one thread at the same time, CPU resource allocation using round-robin strategy;
allocating a time slice to each thread, will switch to the ready state after you use this time slice, so that the CPU so that other threads use ;

8. thread deadlock

8.1 What (What is a deadlock)

Multiple threads in the implementation process, because competing for resources held by the other party has caused each other and can not wait to continue running forever;

8.2 Why (Why deadlock)

Four conditions:

  • Exclusive: resources held in exclusive use, while resources can only be occupied by a thread; (a bowl can only be used by one person)
  • Request and hold: they hold a resource request to hold people's resources, do not release the resources already held, thus blocking; (chopsticks bowl out into others, while not allowing people to own folder)
  • Inalienable: resources have been held not used up before another thread can not be preempted; (and have not yet finished, the bowl can not use to other people)
  • Waiting loop: thread deadlock occurs, a resource - endless chain of resources (e.g., in demo08, ThreadA waiting to acquire and hold resourceA ResourceB, but threadB and opposite, thus constituting a loop waiting condition)

Demo08_DeadLock_Why.java

8.2 How (how to avoid)

Wherein the at least one condition as long as the damage; only request and hold the loop and may be destroyed

Use of resources application of the principle of orderly deadlock can be avoided

Demo08_DeadLock_How.java

  • How to avoid deadlock when ordered allocation of resources?

Code, ThreadA start and at the same time to seize threadB (after) resourceA,
but only one thread may acquire the lock to monitor resourceA, if ThreadA acquired, the threadB only be set until after resourceA sprinkled is released,
this time ThreadA resourceB can continue to acquire the monitor lock, and until after resourceA threadA resourceB are released, ThreadB it
can be activated from a blocked state to thereby avoid deadlock;

9. Daemon threads and user threads

9.1 difference: But the end of the last non-daemon threads, JVM exits normally

For example, gc thread is a daemon, if all the user threads have ended, then there is gc's will be lost meaning

When the current process user thread does not exist, although there daemon running tasks, JVM will directly end
Demo09_DaemonAndUser

Attachment:

Jdk can use the tool to see if jvm jps command is still running;

Linux can also be used ps -eaf | grep java View

9.2 Creating daemon setDaemon (true)

public final void setDaemon(boolean on) {...}

10. ThreadLocal

Multithreading with a range of shared variables, when writing to a shared variable, prone to concurrency issues;

To ensure the security thread, usually it needs to be properly synchronized;

Synchronize concurrent general is locked; need to have some understanding of the lock, increased the burden on the user;

Requirements: After create a variable, each thread to access its own thread is variable;

ThreadLocal can be done;

ThreadLocal to provide a thread-local variable, when the threads access will create a local copy, thereby avoiding the security thread;

10.1 Examples of Use

Demo10_Instance.java

10.2 The principle

Demo10_Principle.java

10.3 does not support inheritance

Namely: the value of the parent thread set, in less than a sub-thread access


**原因: 由get()可见, 调用的是当前线程: **

public T get() {
Thread t = Thread.currentThread();
...
```

10.4 InheritableThreadLocal类

ThreadLocal solve problems does not support inheritance

Rewrite the three methods

Demo10_NoSuppotInheritance.java

Need sub-thread can get ThreadLocal variable secondary thread situation:

  • User login information is stored in the child thread needs to use the parent thread in threadLocal
  • Some middleware requires a unified link id trace the call record

码云: java-concurrent/TheBeautyOfConcurrentProgram/01Base

Guess you like

Origin www.cnblogs.com/52liming/p/11080397.html