Java thread concurrency in collaboration with the timing of the task scheduling

      Multi-threaded environment, we often need concurrency and coordination of multiple threads. This time, we need to understand the importance of a multi-threaded cooperative model "producer / consumer model."

What is a producer?

      Producer refers to a module responsible for production data (here module might be: methods, objects, threads, processes).

What is a consumer?

      Consumers are responsible for processing the data it refers to the module (module here might be: methods, objects, threads, processes).

What is a buffer?

      Consumers can not directly use the data producers, there is a "buffer zone" between them. Producers will produce good data into a "buffer zone", consumer data from a "buffer" to take to be processed.

11-17 Producer Consumer schematic .png

Producer Consumer schematic 11-17

      Buffer is the heart of concurrency, the buffer provided with three benefits:

Concurrent threads to achieve cooperation

      With the buffer after the producer thread only need to be placed inside the buffer data, without the need to manage the situation of consumer spending; likewise, consumers only need to take data from the buffer to handle, does not require producers to produce pipe Case. Thus, to achieve a separation of "producer thread" and "consumer threads" from the logic.

Decoupling of producers and consumers

      You do not need to deal directly with producers and consumers.

Resolve busy uneven, improve efficiency

      When producers slow production data, there are data buffer, it does not affect consumer spending; consumers slow data processing, producers can continue to place the data into the buffer inside.

Producers and consumers modes:

public class TestProduce {
    public static void main(String[] args) {
        SyncStack sStack = new SyncStack();// 定义缓冲区对象;
        Shengchan sc = new Shengchan(sStack);// 定义生产线程;
        Xiaofei xf = new Xiaofei(sStack);// 定义消费线程;
        sc.start();
        xf.start();
    }
}
 
class Mantou {// 馒头
    int id;
 
    Mantou(int id) {
        this.id = id;
    }
}
 
class SyncStack {// 缓冲区(相当于:馒头筐)
    int index = 0;
    Mantou[] ms = new Mantou[10];
 
    public synchronized void push(Mantou m) {
        while (index == ms.length) {//说明馒头筐满了
            try {
               //wait后,线程会将持有的锁释放,进入阻塞状态;
               //这样其它需要锁的线程就可以获得锁;
                this.wait();
                //这里的含义是执行此方法的线程暂停,进入阻塞状态,
                //等消费者消费了馒头后再生产。
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 唤醒在当前对象等待池中等待的第一个线程。
        //notifyAll叫醒所有在当前对象等待池中等待的所有线程。
        this.notify();
        // 如果不唤醒的话。以后这两个线程都会进入等待线程,没有人唤醒。
        ms[index] = m;
        index++;
    }
 
    public synchronized Mantou pop() {
        while (index == 0) {//如果馒头筐是空的;
            try {
                //如果馒头筐是空的,就暂停此消费线程(因为没什么可消费的嘛)。
                this.wait();                //等生产线程生产完再来消费;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        index--;
        return ms[index];
    }
}
 
class Shengchan extends Thread {// 生产者线程
    SyncStack ss = null;
 
    public Shengchan(SyncStack ss) {
        this.ss = ss;
    }
 
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("生产馒头:" + i);
            Mantou m = new Mantou(i);
            ss.push(m);
        }
    }
}
 
class Xiaofei extends Thread {// 消费者线程;
    SyncStack ss = null;
 
    public Xiaofei(SyncStack ss) {
        this.ss = ss;
    }
 
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            Mantou m = ss.pop();
            System.out.println("消费馒头:" + i);
 
        }
    }
}

      Execution result shown in Figure 11-18:

Thread concurrency Collaboration Summary:

      Thread concurrency collaboration (also called thread communication), commonly used for the producer / consumer model, the scenario is as follows:

      1. producers and consumers share the same resources, and the interdependence between producers and consumers, inter-conditional.

      2. For producers, there is no production before the product, consumers should enter the wait state. But after the production of the product, we need to immediately notify consumer spending.

      3. For the consumer, after the consumer, the producer has to inform the consumer end, the need to continue to produce new products for consumption.

      4. producers and consumers, only synchronized is not enough.

        · Synchronized prevents concurrent updates to the same shared resources, to achieve the synchronization;

        · Synchronized message passing can not be used (communication) between the different threads.

      ? 5. That thread is performed messaging (communication) by which methods do see summarized as follows:

Table 11-2 common thread communication method .png

      6. The method of the above methods are java.lang.Object class;

      It can only be used in synchronized method or synchronized block of code, otherwise it will throw an exception.

Note:

      In the actual development, in particular the "architecture", the heavy use of this mode. For beginners to understand, if promoted to senior developers, this is the need to master the content.

Timing task scheduling:

    By Timer and Timetask, we can achieve timing to start a thread.

java.util.Timer

      In this implementation, the Timer class action is an alarm clock function, i.e. the timing or trigger a thread at predetermined time intervals. In fact, Timer class itself is to achieve a thread, but that thread is used to implement calls to other threads.

java.util.TimerTask

      TimerTask class is an abstract class that implements the Runnable interface, multi-threading capabilities class has.

In this implementation, the class through inheritance TimerTask ability to obtain multi-threaded, multi-threaded code will be required to perform writing within the run method and then by performing the Timer class start threads.

java.util.Timer use:

import java.util.Timer;
import java.util.TimerTask;

public class TestTimer {
    public static void main(String[] args) {
        Timer t1 = new Timer();//定义计时器;
        MyTask task1 = new MyTask();//定义任务;
        t1.schedule(task1,3000);  //3秒后执行;
        //t1.schedule(task1,5000,1000);//5秒以后每隔1秒执行一次!
        //GregorianCalendar calendar1 = new GregorianCalendar(2010,0,5,14,36,57); 
        //t1.schedule(task1,calendar1.getTime()); //指定时间定时执行; 
    }
}
 
class MyTask extends TimerTask {//自定义线程类继承TimerTask类;
    public void run() {
        for(int i=0;i<10;i++){
            System.out.println("任务1:"+i);
        }
    }
}

   As shown the results of:

      When you run the above program, you can feel there is a significant delay (probably three seconds!) Before output. There are a few ways I commented out, all try it!

      In actual use, a Timer can be activated any number of threads TimerTask achieved, but there will be blocked between multiple threads. So if you need a completely separate words among multiple threads, it is best to start a TimerTask achieve a Timer.

Note:

      The actual development, we can use open-source framework quanz, more convenient scheduling the timing of the realization of the task. In fact, the content quanz underlying principle is presented here.

Published 150 original articles · won praise 9 · views 20000 +

Guess you like

Origin blog.csdn.net/ZGL_cyy/article/details/104357159