多线程通讯

 使用标志位flag进行共享资源,避免读取数据的重复性。

可以使用wait,即当前线程等待,类似于sleep,可以让当前线程处于休眠状态,和synchronized同时使用,注意wait可以释放锁,而sleep不能释放锁;wait必须和synchronized同时使用,配合 notify 进程状态的唤醒,标志位的切换,因为wait和notify都是在Object类中定义的。

参考代码:

class Res {
	public String userSex;
	public String userName;
	//线程通讯标识
	public boolean flag = false;
}

input类:

class IntThrad extends Thread {
	private Res res;

	public IntThrad(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		int count = 0;
		while (true) {
			synchronized (res) {
				if (res.flag) {
					try {
					   // 当前线程变为等待,但是可以释放锁
						res.wait();
					} catch (Exception e) {

					}
				}
				if (count == 0) {
					res.userName = "小王";
					res.userSex = "男";
				} else {
					res.userName = "小紅";
					res.userSex = "女";
				}
				count = (count + 1) % 2;
				res.flag = true;
				// 唤醒当前线程
				res.notify();
			}

		}
	}
}

output类: 

class OutThread extends Thread {
	private Res res;

	public OutThread(Res res) {
		this.res = res;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (res) {
				if (!res.flag) {
					try {
						res.wait();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				System.out.println(res.userName + "--" + res.userSex);
				res.flag = false;
				res.notify();
			}
		}
	}
}

main:

public class ThreaCommun {
	public static void main(String[] args) {
		Res res = new Res();
		IntThrad intThrad = new IntThrad(res);
		OutThread outThread = new OutThread(res);
		intThrad.start();
		outThread.start();
	}
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Qt 中,可以使用信号和槽机制进行多线程通讯。具体步骤如下: 1. 创建一个 QObject 子类作为线程的工作对象。 2. 在工作对象中定义一个槽函数,用于接收其他线程发送的信号。 3. 创建一个 QThread 对象,并将工作对象移动到该线程中。 4. 在主线程中启动 QThread 对象。 5. 在需要与工作对象通讯的线程中,通过信号与工作对象的槽函数进行连接。 示例代码如下: ``` // 工作对象 class Worker : public QObject { Q_OBJECT public slots: void doWork() { // 工作代码 } signals: void workDone(); }; // 主线程 int main(int argc, char *argv[]) { QApplication a(argc, argv); // 创建工作对象 Worker *worker = new Worker(); // 创建线程并将工作对象移动到线程中 QThread *thread = new QThread(); worker->moveToThread(thread); // 启动线程 thread->start(); // 连接信号和槽函数 QObject::connect(worker, &Worker::workDone, [](){ // 处理工作完成信号 }); // 发送信号 QMetaObject::invokeMethod(worker, "doWork"); return a.exec(); } ``` 在上面的示例代码中,工作对象的 doWork() 函数包含需要在工作线程中执行的代码。当工作完成后,工作对象会发出 workDone() 信号。在主线程中,我们通过 QObject::connect() 将工作对象的 workDone() 信号与一个 lambda 表达式连接起来,以处理工作完成信号。最后,我们通过 QMetaObject::invokeMethod() 在主线程中调用工作对象的 doWork() 函数,触发工作线程的执行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值