关于java:Java-Concurrency-and-Multithreading

82次阅读

共计 1806 个字符,预计需要花费 5 分钟才能阅读完成。

Java Concurrency Concepts

  • Thread actions are implemented by using method run of a Runnable interface.
  • Thread is scheduled to run using start method of a Thread class.
  • Thread scheduler will allocate portions of CPU time (time-slice) to excute thread actions.
  • The return of method main or run terminates the thread.
  • Concurreny doesn’t mean actual phsical parallel execution.
  • In which order threads will actually perform the actions is really not predictable, this is a stochastic process.
  • You can’t put 2 different pieces of logic from different threads to take the same time-slice on the same CPU core.
  • There is some degree of parallelism but it depends.

Thread Life Cycle

  • You can go from whatever state to runnable state (except terminated) and from runnable state to whatever other state except New.
  • Almost every state needs to transit throught the runnable state.
  • Transitions to the running state are not immediate — thread scheduler needs to allocate next available CPU time slot for this thread.
  • boolean b = thread1.isAlive();
    Thread.State phase = thread1.getState();
    Because of the parallelism which is behind the scenes, the state could have changed, in other words, it’s not exactly up-to-date.
  • A thread in a runnable state may check if it has received an interrupt signal.
  • A thread that has entered a waiting or timed waiting state must catch InterruptedException, which puts it back to runnable state, and then decide what it should do.
  • How would the thread react to an interrupt signal is up to the programmer.

Block Thread

Monitor object helps to coordinate order of executions of threads.

  • Any object can be used as a monitor.
  • It allows threads to enter blocked or waiting states.
  • It enables mutual exclusion of threads and signaling mechanisms.
  • synchronized enforces exclusive access to the block of code. A thread would be blocked waiting for the previous thread to complete execution of a synchronized block before it can proceed.
  • If synchronized is used to block against static context, then all the different instances of the same class will be blocking each other against the class itself, as class context is shared among all instances.
正文完
 0