线程
为什么要引入线程
在过去当我们访问一个ftp站点时,经常会出现打不开的现象。是因为机器不够好、网速不够快么?不是,最大的原因在于,我们每一个用户访问服务器,服务器都会把我们当作一个进程,而每个进程是要分配资源的,也就是说当有100个用户同时访问站点,服务器就有100个进程需要处理。而进程是一种heavyweight item,所以比较容易将服务器搞垮。
Whereas each separate process has its own block of memeory, threads are easier on resources because they share memory.
another factor of three in server performance
- Your server can run nine times faster.
- Fewer than a hundred threads can handle thousands of short connections per minutes.
- The impact of running many different threads on the server hardware is relatively minimal.
cost
- developers should concern issues of safety and liveness.Because different threads share the same memory.
- Different threads have to be extremely careful about which resources they use when.
- Attention to deadlock.
Running Threads
Start a thread
Thread t = new Thread();
t.start();
But it has nothing to do.
Two ways to give a thread something to do
- subclass the Thread class and override its
public void run()
method./*For example, a thread that computes primes larger than a stated value could be written as follows:*/ class PrimeThread extends Thread { long minPrime; PrimeThread(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } /*The following code would then create a thread and start it running:*/ PrimeThread p = new PrimeThread(143); p.start();
- Implement the Runnable interface and pass the
Runnable
object to theThread
constructor.(preferred)/*The same example in this other style looks like the following:*/ class PrimeRun implements Runnable { long minPrime; PrimeRun(long minPrime) { this.minPrime = minPrime; } public void run() { // compute primes larger than minPrime . . . } } /*The following code would then create a thread and start it running:*/ PrimeRun p = new PrimeRun(143); new Thread(p).start();
subclass
We are going to implement a subclass of Thread
whose run()
method calculates a 256-bit SHA-2
message digest for a specified file.