java BASIC (thread)

table of Contents

1. Concept

2. Thread the realization

4. Thread State

The concurrency and synchronization

6. communication



First, the concept

1, process: a process corresponds to a program. A process can have multiple threads.

2. Thread: is an independent execution path. It is a program execution flow. CPU as the main body. java in the thread is a virtual CPU, code and data. Code and data are independent of each other. Behavior code and data body constitutes a thread, the thread is determined by the thread body. When you create a virtual CPU thread is automatically encapsulated in the instance of the Thread class.

3, the program is running, even if he did not create a thread, the background will have multiple threads.

4, main () main thread. An inlet for the program.

5, thread scheduling by the scheduler, the order is not considered intervention.

6, the thread's priority: priority setting. Level must be between 1 and 10. And the priority order of execution does not represent

7, daemon threads (daemon): JVM not need to wait executing the daemon thread, setDaemon (true) converted to a daemon

8, Deadlock: multiple threads occupy some shared resources, mutual not released. Waiting for each other. Cause a deadlock.

9, the thread scheduling: a plurality of threads run in a certain order on a single CPU.

Second, three methods to create a thread

  1. Thread inherited interfaces, override run () method

The basic steps: interface inheritance, override the run method, to create a thread object, using the start () open thread.

note:

  • Execution thread must call the start () method can only be added to the scheduler.
  • Join the scheduler may not be executed immediately, waiting for allocation scheduler execution
  • If the direct call to run () method. Not open multiple threads. It calls ordinary method.
    Examples: 1 was added using a thread of execution program 100
public class text extends Thread{//继承Thread
    @Override
    public void run() {    //重写run()方法
        super.run();
        int num = 1;
        
        for(int i = 2; i <= 100; i++) {
            num += i;
        }
        System.out.println("1+2+3+.....+100="+num);
    }
    public static void main(String[] args){
        text tt = new text();//创建线程对象
        tt.start();    //开启线程
    }}

  1. Achieve Runnable
    need to create a thread object, the target object, and then start the thread.
    Advantages: Avoid the limitations of single inheritance. Use interface. Easy sharing.
    Examples: 1 to 100 is calculated using Runnable
public class text implements Runnable{//实现Runnable
    @Override
    public void run() {    //重写run()方法
        int num = 1;
        for(int i = 2; i <= 100; i++) {
            num += i;
        }
        System.out.println("1+2+3+.....+100="+num);
    }
    public static void main(String[] args){ 
        text tt = new text();//创建目标对象
        Thread th = new Thread(tt);//创建线程对象。
        th.start();//开启线程
        //如果是使用一次。可以使用匿名写法。
        //new Thread(tt).start();
    }
}

  1. Callable achieve 
    the required steps: Create a target object, creating implementation services, submitted to the Executive, get results, close the service
    generally go to work after a period of time, it may use to.
public class text implements Callable{//实现Callable
    @Override
    public Object call() throws Exception {//重写call()
        int num = 1;
        for(int i = 2; i <= 100; i++) {
            num += i;
        }
        System.out.println("1+2+3+.....+100="+num);
        return true;
    }
    
    public static void main(String[] args) throws 
    InterruptedException, ExecutionException{
        //(1)创建目标对象
        text tt = new text();
        //(2)创建执行服务
        ExecutorService es = Executors.newFixedThreadPool(1);
        //(3)执行服务
        Future<Boolean> submit = es.submit(tt);
        //(4)获取结果
        boolean object = submit.get();
        //(5)关闭服务
        es.shutdownNow();   
    }
}

Back to top

Fourth, the thread state

Here Insert Picture Description(1) results in a ready state transition method thread:
     call start (), unblocking, calling yield (), the thread switching JVM itself.
(2) method results in blocking state transitions:
     call sleep (), wait (), Join (), IO in the read (), write ()

Several methods:
currentThread: Returns the current thread.
isAlive: to determine whether the current thread alive.
suspend: suspend thread. If you want to restore this thread, other threads must call the resume Resumes the current thread.

(3) a state transition method of a thread

  1. Thread to stop (using boolean)
    the JDK provided by the stop (), destroy () has been abandoned the jdk. So do this
    you can set a boolean value. Be turned on and stop threads.

  2. Thread suspend (sleep)
    can use sleep (time), set the sleep time, to pause a thread effect.
    Time is the number of milliseconds. Moreover, sleep will not release the lock.

  3. Thread comity (yield)
    comity thread is the current thread suspended. Instead of blocking the current thread into the ready state from running. Let cpu reschedule.

  4. Thread jump the queue (Join)
    to jump the queue, the thread is blocked currently running. Waiting to jump the queue thread execution is over. In other threads to execute. It is a blocking state.

  5. interrupt
    If a thread is in the blocked cell using the interrupt method will allow the thread interrupt status is cleared. And the thread will receive InterruptExcaption exception.

Back to top

Fifth, concurrency and synchronization

  1. Concurrency: simultaneous operation is the same object multiple threads.
  2. Sync: is a waiting mechanism. Multiple threads need access to the same object into the waiting queue forming pools. After the need to wait in front of the thread used up, the next thread and then use this resource.
  3. Critical regions: a program code segment in separate, concurrent threads to access the same object, and may be block.
  4. Lock Object: each object designated by a lock arranged to synchronize statement. It is a unique exclusive lock. If a thread to acquire the lock object, the operation will have the right to object, any other threads can not carry out any operations on the object.

Security thread: the need to form a queue, and a lock mechanism.

  1. After obtaining the exclusive lock object, exclusive resources, other threads must wait
  2. Multithreading competition, lock, resulting in the release of the lock more context switching and scheduling delay. Cause performance problems
  3. If a high priority thread to wait for a lower priority thread, priority will lead, causing performance problems

Lock mechanism, synchronize block

  1. Each object corresponds to a lock, a synchronize every method must call the method of obtaining the object lock can perform. Otherwise, the thread is blocked. Method, if implemented, will be the exclusive lock. Until method returns, it will lock release. Blocked thread can acquire the lock to re-enter the executable state.
  2. synchronize sync block: synchronize (obj) {}, obj called synchronization monitor
    any object can be used as synchronization monitor.
    The synchronization method without specifying synchronization monitor, because synchronization monitor synchronization method is the object itself.
    Container CopyOnWriteArrayList <type> have been integrated in the locking mechanism.

Back to top

Six, communication

Here Insert Picture Description
 In the picture. When there is a warehouse of goods, consumers need to be informed. Then, when no goods, inform the producer
of such a transfer (communication) of the message

Because synchronize sync blocks, prevents concurrent updates to the same shared resources to achieve synchronization. However, it can not achieve communication problems between the different threads.

Solve a communication problem:

  1. What method can only be used in the synchronization method or synchronous code. You can solve communication problems.
    wait (): thread wait until the thread notifications. And sleep () different. It will release the lock.
    notifiy (): wake up a thread in a wait state
    ontifyAll (): wake-up call to all the thread wait () method on the same object. High-priority scheduling priority

  2. Tube-
    concurrent collaboration model "producer / consumer model" is the tube.
    Set up a buffer zone between producers and consumers. There is a data container, consumers can consume,
    data is empty, waiting for consumers, producers can be produced. Data is full, wait producer

  3. Be boolean settings. Like lights as     
    it is the use of Boolean value, setting switch Note: Do not forget that after waiting, need to switch back.

  4. Regular schedule
    using the Timer, Timetask achieve timing to start a thread.

Back to top

Published 12 original articles · won praise 0 · Views 110

Guess you like

Origin blog.csdn.net/weixin_44304524/article/details/104862777