线程间通信 [英] Inter-threads communication

查看:103
本文介绍了线程间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最简单的实现是当我们从单类main方法调用其他类实现runnable:

The easiest implementation is when we call from single class main method other classes implementing runnable:

 public static void main(String [] args){

    // declarations ...


    receiver.start();
    player.start();


 }

接收一个数据包值,我想发送该值到第二个线程。如何做呢?

Say inside receiver I have while loop which receives a packet value and I want to send that value to the second thread. How to do that?

为了说明我还不关心一个线程控制另一个线程,我只想让第一个线程与第二个共享值。

Just to clarify I don't yet care about one thread controlling another, I just want first thread to share values with second.

和小问题一起 - JDK 7 Fork真的大大提高了java并发api的性能吗?

And tiny question aside - does JDK 7 Fork really dramatically increases performance for java concurrent api?

谢谢你的时间,

推荐答案

一个简单的选择是使用 java.util.concurrent.atomic.AtomicReference (或其他 Atomic ... classes )。创建 AtomicReference 的单个实例,并将其传递给各个线程运行的代码,并设置来自接收者线程的值。其他线程随后可以以线程安全的方式读取这些值。

A simple option is to use a java.util.concurrent.atomic.AtomicReference (or one of the other Atomic... classes). Create a single instance of AtomicReference, and pass it to the code that the various threads run, and set the value from the receiver thread. The other thread(s) can then read the value at their leisure, in a thread-safe manner.


提高java并发api的性能?

does JDK 7 Fork really dramatically increases performance for java concurrent api?

不,它只是一个新的API,使一些事情更容易。它不是为了使事情更快。

No, it's just a new API to make some things easier. It's not there to make things faster.

这篇关于线程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆