如何从BlockingQueue的对象中获取数据?

时间:2022-06-02 20:57:01

I have class for an object with all the fields and getters. Now, one thread is putting some data into it, in my case

我有一个包含所有字段和getter的对象的类。现在,在我的情况下,一个线程正在将一些数据放入其中

object = new MyObject(int, int, char, int) 
queue.put(object);

and then puts it into BlockingQueue, then the second thread is taking this object

然后将其放入BlockingQueue,然后第二个线程正在使用此对象

MyObject toSolve = queue.take();

My question is how to take the data from object to make operations using its ints.

我的问题是如何从对象获取数据以使用其int进行操作。

1 个解决方案

#1


Surely you don't actually mean you're using Object? If yes, then I'm guessing your problem is that you put a YourClass on the queue, but get an java.lang.Object out.

当然,你实际上并不是说你正在使用Object?如果是,那么我猜你的问题是你把一个YourClass放在队列中,但得到一个java.lang.Object。

If you look at BlockingQueue you'll see it is genericized, so writing something like (notice the <>'s)

如果你看看BlockingQueue你会看到它是通用的,所以写一些像(注意<>的)

BlockingQueue bq = new BlockingQueue<YourClass>();
bq.put( new YourClass( 1 , 2 , 'a' , 42 ) );

then

YourClass yq = bq.take();

will work like a charm, both in terms of compilation and function, and you can use the getters on yq to obtain your int's and char.

在编译和功能方面都会像魅力一样工作,你可以在yq上使用getter来获取你的int和char。

Use generics, that's what they're there for.

使用泛型,这就是他们的用途。

Cheers,

#1


Surely you don't actually mean you're using Object? If yes, then I'm guessing your problem is that you put a YourClass on the queue, but get an java.lang.Object out.

当然,你实际上并不是说你正在使用Object?如果是,那么我猜你的问题是你把一个YourClass放在队列中,但得到一个java.lang.Object。

If you look at BlockingQueue you'll see it is genericized, so writing something like (notice the <>'s)

如果你看看BlockingQueue你会看到它是通用的,所以写一些像(注意<>的)

BlockingQueue bq = new BlockingQueue<YourClass>();
bq.put( new YourClass( 1 , 2 , 'a' , 42 ) );

then

YourClass yq = bq.take();

will work like a charm, both in terms of compilation and function, and you can use the getters on yq to obtain your int's and char.

在编译和功能方面都会像魅力一样工作,你可以在yq上使用getter来获取你的int和char。

Use generics, that's what they're there for.

使用泛型,这就是他们的用途。

Cheers,