start suspend resume stop

package scjp;

import com.sun.corba.se.impl.ior.NewObjectKeyTemplateBase;

class MyThread implements Runnable{

	@Override
	public void run() {
		// TODO Auto-generated method stub
		int i=0;
		while (true) {
			System.out.println(Thread.currentThread().getName() + " i " + i++);
		}
	}
}

public class DemoThreadResume{
	
	
	Thread thread;
	
	public DemoThreadResume(String name) {
		// TODO Auto-generated constructor stub
		thread=new Thread(new MyThread());
		thread.setName(name);
	}

	
	
	public static void main(String[] args) {
		DemoThreadResume demoThreadResume=new DemoThreadResume("Runnning Thread");
		System.out.println("Starting ");
		demoThreadResume.thread.start();
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		demoThreadResume.thread.suspend();
		demoThreadResume.thread.resume();
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		demoThreadResume.thread.stop();
		
	}
	
}



这段code里专门列出了线程的这几种方法的调用.首先start,然后suspended,然后resum,然后stop.
我在调试这段代码的时候遇到了一个问题,如果在
demoThreadResume.thread.suspend();
demoThreadResume.thread.resume();

中间加入System.out.println("Suspend ... ");
线程将会阻塞,而不执行.debug后才发现System.out.println是同步方法,因为已经呗前面的Thread拥有所以不能被后面的使用,这是不是也是resume的一个特点呢,虽然挂起,仍然拥有锁(这里是这个println方法的锁).下面是println方法的源代码.
  /**
     * Prints a String and then terminate the line.  This method behaves as
     * though it invokes <code>{@link #print(String)}</code> and then
     * <code>{@link #println()}</code>.
     *
     * @param x  The <code>String</code> to be printed.
     */
    public void println(String x) {
	synchronized (this) {
	    print(x);
	    newLine();
	}
    }

你可能感兴趣的:(thread,sun)