⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ch3.txt

📁 精通Java网络编程代码全部
💻 TXT
字号:
/* 代码3-1
 * Created on 2005-5-14
 */
 
 public class SimThread extends Thread {
  private int count = 7;
  private static int threadCount = 0;
  private int threadNumber = ++threadCount;
  public SimpleThread() {
    System.out.println("Making " + threadNumber);
  }
//run()方法是在实现Thread类的过程中一定要实现的方法
  public void run() {
    while(true) {
      System.out.println("Thread " + 
        threadNumber + "(" + countDown + ")");
      if(--count == 0) return;
    }
  }
  public static void main(String[] args) {
//循环启动五个线程
    for(int i = 0; i < 5; i++)
{
      new SimThread().start();
    System.out.println("All the Threads Started");
  }
}

/* 代码3-2
 * Created on 2005-5-14
 */
 
 import java.util.*;
class TimePrinter implements Runnable {
	int pauseTime;
	String name;
	public TimePrinter(int x, String n) {
		pauseTime = x;
		name = n;
	}
	//run函数作为Runnable接口要实现出来
	public void run() {
		while(true) {
			try {
				System.out.println(name + ":" + new 
					Date(System.currentTimeMillis()));
				//实现线程的休眠
				Thread.sleep(pauseTime);
			} catch(Exception e) {
				System.out.println(e);
			}
		}
	}
	static public void main(String args[]) {
		//创建线程t1
		Thread t1 = new Thread(new TimePrinter(1000, "Fast Guy"));
		t1.start();
		Thread t2 = new Thread(new TimePrinter(3000, "Slow Guy"));
		t2.start();
	}
}



 
 
 
 
 

/* 代码3-3
 * Created on 2005-5-14
 */
 
 try{
	//表示要等待1秒
	lock.wait(1000);
}
catch(InterruptedException e){
	System.out.println("cannot obtain the lock after 1000 ms.");
}


/* 代码3-4
 * Created on 2005-5-14
 */
 package Thread;

public class Deadlock implements Runnable {
	A a = new A();
	B b = new B();
	
	Deadlock(){
		System.out.println("Press Ctrl-C to get out of deadlock.");
		Thread.currentThread().setName("ThreadA ");
		Thread t = new Thread(this,"ThreadB");
		t.start();
		
		//调用方法对象a的方法method1,
		//从而获得队对象a的锁,在此方法中继续得到对象b的锁;
		//但是此时对象a的锁已不可得,因此死锁发生
		a.method1(b);
		System.out.println("back into main thread(ThreadA)");
	}
	
	public void run() {
		//调用方法对象b的方法method1,
		//从而获得队对象b的锁,在此方法中继续得到对象a的锁;
		//但是此时对象a的锁已不可得,因此死锁发生
		b.method1(a);
		System.out.println("back into child thread(ThreadB)");
	}
	
	public static void main(String[] args){
		new Deadlock();
	}
}

class A{
	//同步方法,执行这个方法前需要获得对象的锁,方法method2同样
	synchronized void method1(B b){
		String name = Thread.currentThread().getName();
		System.out.println(name + " inside A.method1");
		try{
			Thread.sleep(1000);//表示暂停一秒
		}
		catch(Exception e) {
			System.out.println("A interrupted!");
		}
		System.out.println(name + " waiting for B.method2");
		b.method2();		
	}
	
	synchronized void method2(){
		System.out.println("inside A.method2");		
	}
}

class B{
	//同步方法,执行这个方法前需要获得对象的锁,方法method2同样
	synchronized void method1(A a){
		String name = Thread.currentThread().getName();//获取当前线程的名字
		System.out.println(name + " inside B.method1");
		try{
			Thread.sleep(1000); //表示暂停一秒
		}
		catch(Exception e) {
			System.out.println("B interrupted!");//打印错误信息
		}
		System.out.println(name + " waiting for A.method2");
		a.method2();		
	}
	
	synchronized void method2(){
		System.out.println("inside B.method2");		
	}
}

/* 代码3-5
 * Created on 2005-5-14
 */
 //ThreadPool.java
package org.jutils.runtime;
import java.lang.*;
import java.util.*;
public class ThreadPool {
	private static ThreadPool instance_ = null;
	//定义优先级别常数,空闲的线程按照优先级不同分别存放在三个vector中
	public static final int LOW_PRIORITY = 0; 
	public static final int NORMAL_PRIORITY = 1;
	public static final int HIGH_PRIORITY = 2;
	//保存空闲线程的List,或者说它是"池"
	private List[] idleThreads_;  
	private boolean shutDown_ = false;
	private int threadCreationCounter_; //以创建的线程的个数
	private boolean debug_ = false;    //是否输出调试信息
	//构造函数,因为这个类视作为singleton实现的,因此构造函数为私有
	private ThreadPool() {       
		// 产生空闲线程.
		//三个vector分别存放分别处在三个优先级的线程的引用
		List[] idleThreads = {new Vector(5), new Vector(5), new Vector(5)};
		idleThreads_ = idleThreads;
		threadCreationCounter_ = 0;
	}
	
	public int getCreatedThreadsCount() {
		return threadCreationCounter_;
	}
	//通过这个函数得到线程池类的实例
	public static ThreadPool instance() {
		if (instance_ == null)
			instance_ = new ThreadPool();
		return instance_;
	}
	
	public boolean isDebug() {
		return debug_;
	}
	
	//将线程repoolingThread从新放回到池中,这个方式是同步方法。
	//这个方法会在多线程的环境中调用,设计这个方法的目的是让工作者线程
	//在执行完target中的任务后,调用池类的repool()方法,
	//将线程自身从新放回到池中。只所以这么做是因为线程池并不能预见到
	//工作者线程何时会完成任务。参考PooledThread的相关代码。
	protected synchronized void repool(PooledThread repoolingThread) {
		if (!shutDown_) {
			if (debug_) {
				System.out.println("ThreadPool.repool() : repooling ...");
			}
			switch (repoolingThread.getPriority()) {
			case Thread.MIN_PRIORITY :
				{
					idleThreads_[LOW_PRIORITY].add(repoolingThread);
					break;
				}
			case Thread.NORM_PRIORITY :
				{
					idleThreads_[NORMAL_PRIORITY].add(repoolingThread);
					break;
				}
			case Thread.MAX_PRIORITY :
				{
					idleThreads_[HIGH_PRIORITY].add(repoolingThread);
					break;
				}
			default :
				throw new IllegalStateException("Illegal priority found while repooling a Thread!");
			}
			notifyAll();//通知所有的线程
		}
		else {
			if (debug_) {
				System.out.println("ThreadPool.repool() : Destroying incoming thread....");
			}
			repoolingThread.shutDown();//关闭线程
		}
		if (debug_) {
			System.out.println("ThreadPool.recycle() : done.");
		}
	}
	
	public void setDebug(boolean newDebug) {
		debug_ = newDebug;
	}
	
	//停止池中所有线程
	public synchronized void shutdown() {
		shutDown_ = true;
		if (debug_) {
			System.out.println("ThreadPool : shutting down ...");
		}
		for (int prioIndex = 0; prioIndex <= HIGH_PRIORITY; prioIndex++) {
			List prioThreads = idleThreads_[prioIndex];
			for (int threadIndex = 0; threadIndex < prioThreads.size(); threadIndex++) {
				PooledThread idleThread = (PooledThread) prioThreads.get(threadIndex);
				idleThread.shutDown();
			}
		}
		notifyAll();
		if (debug_) {
			System.out.println("ThreadPool : shutdown done.");
		}
	}
	
	//以Runnable为target,从池中选择一个优先级为priority的线程创建线程
	//并让线程运行。
	public synchronized void start(Runnable target, int priority) {
		PooledThread thread = null;  //被选出来执行target的线程
		List idleList = idleThreads_[priority];
		if (idleList.size() > 0) {
			//如果池中相应优先级的线程有空闲的,那么从中取出一个
			//设置它的target,并唤醒它
			//从空闲的线程队列中获取
			int lastIndex = idleList.size() - 1;
			thread = (PooledThread) idleList.get(lastIndex);
			idleList.remove(lastIndex);
			thread.setTarget(target);
		}
		//池中没有相应优先级的线程
		else { 
			threadCreationCounter_++;
			// 创建新线程,
			thread = new PooledThread(target, "PooledThread #" + threadCreationCounter_, this);
			// 新线程放入池中
			switch (priority) {
			case LOW_PRIORITY :
				{
					thread.setPriority(Thread.MIN_PRIORITY);
					break;
				}
			case NORMAL_PRIORITY :
				{
					thread.setPriority(Thread.NORM_PRIORITY);
					break;
				}
			case HIGH_PRIORITY :
				{
					thread.setPriority(Thread.MAX_PRIORITY);
					break;
				}
			default :
				{
					thread.setPriority(Thread.NORM_PRIORITY);
					break;
				}
			}
			//启动这个线程
			thread.start();
		}
	}
}
/* 代码3-6
 * Created on 2005-5-14
 */
 //PooledThead.java
package org.jutils.runtime;

public class PooledThread extends Thread {
	private ThreadPool pool_;  // 池中线程需要知道自己所在的池
	private Runnable target_;   // 线程的任务
	private boolean shutDown_ = false;
	private boolean idle_ = false;//设置是否让线程处于等待状态
	
	private PooledThread() {
		super();
	}
	
	private PooledThread(Runnable target) {
		super(target); //初始化父类
	}
	
	private PooledThread(Runnable target, String name) {
		super(target, name);
	}
	
	public PooledThread(Runnable target, String name, ThreadPool pool) {
		super(name);
		pool_ = pool;
		target_ = target;
	}
	
	private PooledThread(String name) {
		super(name);//初始化父类
	}
	
	private PooledThread(ThreadGroup group, Runnable target) {
		super(group, target);
	}
	
	private PooledThread(ThreadGroup group, Runnable target, String name) {
		super(group, target, name);
	}
	
	private PooledThread(ThreadGroup group, String name) {
		super(group, name);
	}
	
	public java.lang.Runnable getTarget() {
		return target_;
	}
	
	public boolean isIdle() {
		return idle_;//返回当前的状态
	}
	
	//工作者线程与通常线程不同之处在于run()方法的不同。通常的线程,
	//完成线程应该执行的代码后,自然退出,线程结束。
	//虚拟机在线程结束后收回分配给线程的资源,线程对象被垃圾回收。]
	//而这在池化的工作者线程中是应该避免的,否则线程池就失去了意义。
	//作为可以被放入池中并重新利用的工作者线程,它的run()方法不应该结束,
	//随意,在随后可以看到的实现中,run()方法执行完target对象的代码后,
	//就将自身repool(),然后调用wait()方法,使自己睡眠而不是退出循环和run()。
	//这就使线程池实现的要点。
	public void run() {
		// 这个循环不能结束,除非池类要求线程结束
		// 每一次循环都会执行一次池类分配给的任务target
		while (!shutDown_) {  
			idle_ = false;
			if (target_ != null) {
				target_.run();  // 运行target中的代码
			}
			idle_ = true;
			try {
				//线程通知池重新将自己放回到池中
				pool_.repool(this);  // 
				//进入池中后睡眠,等待被唤醒执行新的任务,
				//这里是线程池中线程于普通线程的run()不同的地方。
				synchronized (this) {
					wait();
				}
			}
			catch (InterruptedException ie) {
			}
			idle_ = false;
		}
		//循环这里不能结束,否则线程结束,资源被VM收回,
		//就无法起到线程池的作用了
	}
	
	//设置新的target,并唤醒睡眠中的线程
	public synchronized void setTarget(java.lang.Runnable newTarget) {
		target_ = newTarget;  // 新任务
		notifyAll();          // 唤醒睡眠的线程
	}
	
	public synchronized void shutDown() {
		shutDown_ = true;
		notifyAll();
	}
}

/* 代码3-7
 * Created on 2005-5-14
 */
 在类ThreadPool中添加下面的main()方法
public static void main(String[] args) {
	System.out.println("Testing ThreadPool ...");
	System.out.println("Creating ThreadPool ...");
	ThreadPool pool = ThreadPool.instance();
	pool.setDebug(true);
	class TestRunner implements Runnable {
		public int count = 0;
		public void run() {
			System.out.println("Testrunner sleeping 5 seconds ...");
			//此方法使本线程睡眠5秒
			synchronized (this) {
				try {
					wait(5000);//等待5秒时间
				}
				catch (InterruptedException ioe) {
				}
			}
			System.out.println("Testrunner leaving  ...");
			count++;
		}
	}
	System.out.println("Starting a new thread ...");
	TestRunner runner = new TestRunner();
	pool.start(runner, pool.HIGH_PRIORITY);
	System.out.println("count : " + runner.count);
	System.out.println("Thread count : " + pool.getCreatedThreadsCount());
	pool.shutdown();
}

 
 
 

 

 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -