java: New to threads. Is this possible?
I'll try to be short.
Need a number of threads to open sockets (each thread opens one socket) and make HTTP Requests. I am new to multi-threaded and I don't know if this is possible, since each thread must be running until the request is finished (i think).
开发者_运维技巧[edit after comments]
I don't know if this is possible since currently running thread can be suspended before the response is fetched.
Thanks for any help.
It sounds like a Thread pool is what you need.
There is a section in the Java Concurrency Tutorial about them.
(This is pretty heavy stuff for a beginner though)
Yep, definately possible.
In response to your further query
The fact that a thread is suspended doesn't stop it from recieving data over a socket. If any data arrives while the thread is suspended it is queued until the thread resumes.
What do you mean by "suspended"? If you refer to the context-switching between threads, then you have some holes in your understanding of multi threading. It is the same as multi tasking in a OS: You're running Word and Explorer at the same time on your machine, and the one application doesn't die when the other needs to run - the operating system instead puts one process/thread into wait by saving all its state, then retrieves all state for the next thread and then sets it into motion. This goes back and forth so fast that it seems like they run at the same time - but on a single-processor machine, only one thread really runs at any specific time.
The thread itself doesn't "know" this - only if it continuously run in a tight loop checking the time, it will notice that the time jerks: The time increases smoothly for some milliseconds, but then suddenly the time jumps forward and then still runs smoothly for a new set of milliseconds. The jump is when another thread was running. Each such period of smooth running is called a time slice, or quantum. But if the thread doesn't need the processor, e.g. when it waits for I/O, then the OS takes it back before the time slice is over.
The thread exits (dies) when you exit/return from the run() method - not before.
For fetching multiple HTTP connections, multi threading is ideal: The thread will use most of the time waiting for incoming bytes on the network - and while it waits, the OS knows this and sticks the thread into "IO wait", instead running other threads in the mean time (or just wastes away cycles if no thread needs to run, e.g. everyone is waiting for IO - or in these days, the processor throttles down).
Yes, what you describe is very typical amongst java programs that retrieve data via HTTP.
Yes, this is possible.
Look here: http://andreas-hess.info/programming/webcrawler/index.html
or google for "java multi thread web crawler"
精彩评论