I want to create different thread for read and write method by using socket. I wonder should I use different socket or same socket to share for both thread?
If you're reading and writing to and from the same device/object, i'd use the same thread. This way you don't have it trying to read something when you haven't written to it yet. Doing multiple threads might cause a multitude of errors if you're not careful, such as nulls.
You can use the same socket to both read and write. Of course one of the 2 endpoints must open a server socket. Then you can have 1 thread blocked waiting for input data while another thread could output data when needed
1. Create One socket object .
2. Use any nos of threads to access this object, but do keep enough care to make the write and read operations Thread-Safe
.
3. Try using the ServerChannel
and ServerSocketChannel
from java.util.nio
package, which is Asynchronous .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.