`

Worker Thread

 
阅读更多

        这个模型也称为背景线程。把工作交个被人,让别人启动一个线程做交给的任务,自己继续做自己的事,这是Thread Per Message。而在Worker Thread中,任务交给别人后,并不是每次都开启一个线程,而是不断的重复利用已有的线程。事实上开启一个线程是很耗费时间的工作。

        实例中:Request是委托者,它有execute功能。WorkThread不断的从队列中获取Request,然后让Request执行。ClientThread不断的向队列中添加Request。而“队列”Channel中,如果满了,添加会等待,如果空了,获取会等待。Channel中有一列WorkThread,用来不断的获取Request。这个实例中请求者和工人数量都是多个的。

         ClientThread不断的请求新任务,Channel里面的几个WorkerThread不断的解决请求。

import java.util.Random;

public class Request {
	private final String name;  //委托者
	private final int number;  //请求编号
	private static final Random random=new Random();
	public Request (String name,int number){
		this.name=name;
		this.number=number;
	}
	public void execute(){
		System.out.println(Thread.currentThread().getName()+" executes "+this);
		try{
			Thread.sleep(random.nextInt(1000));
		}catch(InterruptedException e){
			e.printStackTrace();
		}
	}
	public String toString(){
		return " [Request from "+name +" No."+number+"]";
	}

}

 

import java.util.Random;

public class ClientThread extends Thread{
	private final Channel channel;
	private static final Random random=new Random();
	public ClientThread(String name,Channel channel){
		super(name);
		this.channel=channel;
	}
	public void run(){
		try{
			for(int i=0;true;i++){
				Request request=new Request(getName(),i);
				channel.putRequest(request);
				Thread.sleep(random.nextInt(1000));
			}
		}catch (InterruptedException e){
			e.printStackTrace();
		}
	}

}

 

public class WorkerThread extends Thread{
    private final Channel channel;
    public WorkerThread(String name,Channel channel){
    	super(name);
    	this.channel=channel;
    }
    public void run(){
    	while(true){
    		Request request=channel.takeRequest();
    		request.execute();
    	}
    }
}

 

public class Channel {
	private static final int MAX_REQUEST=100;
	private final Request[] requestQueue;
	private int tail;    //下一个putRequest
	private int head;    //下一个takeRequest
	private int count;    //Request的数量
	private final WorkerThread[] threadPool;
	public Channel(int threads){
		this.requestQueue=new Request[MAX_REQUEST];
		this.head=0;
		this.tail=0;
		this.count=0;
		threadPool=new WorkerThread[threads];
		for(int i=0;i<threadPool.length;i++){
			threadPool[i]=new WorkerThread("Worker-"+i,this);
		}
	}
	public synchronized void startWorkers(){
		for(int i=0;i<threadPool.length;i++){
			threadPool[i].start();
		}
	}
	public synchronized void putRequest(Request request){
		while(count>=requestQueue.length){
			try{
				wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		requestQueue[tail]=request;
		tail=(tail+1)%requestQueue.length;
		count++;
		notifyAll();
	}
	public synchronized Request takeRequest(){
		while(count<=0){
			try{
				wait();
			}catch(InterruptedException e){
				e.printStackTrace();
			}
		}
		Request request=requestQueue[head];
		head=(head+1)%requestQueue.length;
		count--;
		notifyAll();
		return request;
	}

}

 

public class Main {
	public static void main(String[] args){
		Channel channel=new Channel(5);
		channel.startWorkers();
		new ClientThread("Alice",channel).start();
		new ClientThread("Bobby",channel).start();
		new ClientThread("Chris",channel).start();
	}
}

 运行结果:

Worker-3 executes  [Request from Alice No.0]
Worker-1 executes  [Request from Bobby No.0]
Worker-0 executes  [Request from Chris No.0]
Worker-4 executes  [Request from Chris No.1]
Worker-2 executes  [Request from Alice No.1]
Worker-4 executes  [Request from Chris No.2]
Worker-0 executes  [Request from Alice No.2]
Worker-3 executes  [Request from Bobby No.1]
Worker-1 executes  [Request from Alice No.3]
Worker-4 executes  [Request from Bobby No.2]
Worker-2 executes  [Request from Alice No.4]
Worker-4 executes  [Request from Chris No.3]
Worker-3 executes  [Request from Bobby No.3]
Worker-3 executes  [Request from Alice No.5]
Worker-0 executes  [Request from Alice No.6]
Worker-0 executes  [Request from Alice No.7]
Worker-1 executes  [Request from Alice No.8]
Worker-0 executes  [Request from Chris No.4]
Worker-4 executes  [Request from Bobby No.4]
Worker-0 executes  [Request from Alice No.9]
Worker-1 executes  [Request from Chris No.5]
Worker-2 executes  [Request from Chris No.6]
Worker-0 executes  [Request from Alice No.10]

。。。

 

 

 

 

 

 

分享到:
评论

相关推荐

    线程示例WorkerThread_demo

    `WorkerThread_demo`是一个典型的线程应用示例,它可能是为了展示如何在C#环境中创建和管理后台工作线程,以实现非阻塞的UI交互。下面我们将详细探讨线程的概念,`WorkerThread`类的设计,以及可能的实现方式。 ...

    C#建立WorkerThread

    WorkerThread线程实例,C#建立WorkerThread "工作者线程"的例子,代码中已定义工作者线程中调用的公用委托,建立事件标识,用于停止线程,建立委托实例,用于调用接口函数,自定义了一个工作者线程处理函数,若停止...

    Android代码-mainthread和WorkerThread线程之间的通信助手库

    AndroidChannel is helper library for inter thread communication between main thread and worker thread. AndroidChannel uses HandlerThread for inter thread communication. Setup Gradle dependencies { .....

    Exemplo-Manager Worker Thread System.pdf

    ### Manager Worker Thread System 在《Exemplo-Manager Worker Thread System.pdf》文档中,我们深入了解了一个基于Delphi的多线程系统的设计与实现方法。本文档不仅适用于Delphi开发者,也适用于那些希望了解如何...

    WorkerThread_Vc_

    本示例"WorkerThread_Vc_"提供了一种创建和管理Worker线程的方法,包括如何启动线程、传递参数以及与主线程进行通信。 首先,要创建一个线程,我们需要定义一个函数,这个函数将在新线程中运行,我们通常称之为线程...

    worker_thread_class.zip_c# Thread类_event class

    public class WorkerThread : BaseClass { public delegate void WorkCompletedEventHandler(object sender, EventArgs e); public event WorkCompletedEventHandler WorkCompleted; private void ...

    QT+moveToThread线程+connect信号槽+信号返回值

    connect(workerThread, &QThread::finished, workerThread, &QThread::deleteLater); // 启动工作线程 workerThread-&gt;start(); ``` 在这个例子中,`WorkerObject`被移动到`workerThread`,当`doWork`信号被发出时...

    QT 5.15.2 move to thread用法示例

    然后在`main`函数中,我们创建了一个QThread实例`workerThread`和一个`Worker`对象`worker`。通过`moveToThread`方法,我们将`worker`移动到`workerThread`中。当工作线程启动时,`doWork`槽会被调用,执行耗时任务...

    Qt UDP QUdpSocket多线程实例 movetothread

    class WorkerThread : public QThread { public: void run() override; }; ``` 2. 在`run()`方法中,创建`QUdpSocket`实例,并设置必要的属性,如绑定的端口号。 ```cpp void WorkerThread::run() { ...

    opencv3.0交叉编译用parallel.cpp

    在ubuntu14.04中交叉编译中用到的parallel.cpp,地址在opencv-3.0.0/modules/core/src/parallel.cpp,详细步骤可参考我的博客http://blog.csdn.net/u012354697/article/details/50655597

    c++ thread event

    在这个例子中,`worker_thread`会等待`ready`变为`true`,而`main_thread`在准备好后会设置`ready`并唤醒`worker_thread`。这就是通过条件变量模拟线程事件的一种方式。 C++标准库还提供了`std::future`和`std::...

    Qt 使用多线程QThread实现进度条

    2. 在主线程中创建`WorkerThread`实例,并连接信号和槽:在UI线程中创建`WorkerThread`对象,并将其progressUpdated信号连接到进度条的setValue()槽。这样,当后台线程更新进度时,UI会自动响应。 ```cpp Worker...

    Worker_tsat.zip

    1. **工作线程(Worker Thread)**:在多线程编程中,工作线程是负责执行特定任务的线程。它们通常用于处理I/O操作、计算密集型任务或长时间运行的进程,以避免阻塞主线程,提高应用程序的响应性和效率。 2. **任务...

    C#多线程编程笔记

    Thread workerThread = new Thread(workerThreadStart); // 创建线程 workerThread.Start(); // 启动线程 Console.WriteLine("Main Thread: Worker thread started."); Console.ReadLine(); // 非正常结束线程...

    Qt 继承object 多线程例子

    connect(&workerThread, &QThread::finished, &worker, &QObject::deleteLater); // 启动线程 workerThread.start(); return app.exec(); } ``` 在这个例子中,我们创建了一个`Worker`类继承自`QObject`,并...

    vs2015+QT5Qt GUI程序主窗体与子线程QThread通信实例

    connect(&workerThread, &WorkerThread::finished, &workerThread, &QObject::deleteLater); // 确保子线程结束时删除自身 connect(&mainWindow, &MainWindow::startSignal, &workerThread, &WorkerThread::doWork);...

    threads.rar

    WorkerThread *thread = new WorkerThread(); worker-&gt;moveToThread(thread); ``` 启动线程并连接信号与槽,当线程开始运行时,会调用Worker的doWork()方法: ```cpp connect(thread, &QThread::started, worker, ...

    Qt 多线程采用继承QObject方式编写

    WorkerThread *worker = new WorkerThread; worker-&gt;moveToThread(thread); ``` 3. **信号与槽的连接**:为了在主线程和工作线程之间进行通信,你需要定义信号和槽。通常,你会在主线程中发射一个信号来启动工作,...

    QThread应用实例

    explicit WorkerThread(QObject *parent = nullptr) : QThread(parent) {} protected: void run() override { // 在这里执行耗时任务 for (int i = 0; i ; ++i) { // 做一些计算或I/O操作 } emit ...

    moveToThreadDemo.rar

    connect(&app, &QApplication::started, &workerThread, &QThread::start); connect(&worker, &Worker::resultReady, &app, [](int result) { // 处理结果 qDebug() ; }); // 从主线程发送信号 worker....

Global site tag (gtag.js) - Google Analytics