ITeye博客

Java多线程之基础操作

BlueCore · 2009-10-14 20:54 · Java SE · Markdown

参考自http://developer.51cto.com/art/200906/132339.htm 及其一系列的网页。做个汇总。

一:创建并运行线程:

通过继承Thread,重载其*public void run()*;或者实现Runnable接口, 建立线程;

      RunnableT t1 = new MyRunnable();             //RunnableT 为实现runnable接口的类
      Thread thread1 = new Thread(t1, "MyThread1"); //线程名为MyThread1
      Thread thread2 = new Thread(t1); 

          调用start()方法运行线程;调用isAlive()方法查看线程是否运行状态

二:挂起和唤醒线程: suspend()/resume() 是deprecated方法,suspend()可以挂起其他线程,sleep()仅能休眠自己...sleep方法需要捕捉异常,当其休眠的时候使用其interrupt方法中断线程会抛出InterruptedException异常

三:终止或者中断线程的方法:

1,使用退出标识终止


 public class ThreadFlag extends Thread  
 {  
     public volatile boolean exit = false;  
  
     public void run()  
     {  
         while (!exit);  
     }  
     public static void main(String[] args) throws Exception  
     {  
         ThreadFlag thread = new ThreadFlag();  
         thread.start();  
         sleep(5000); // 主线程延迟5秒  
         thread.exit = true;  // 终止线程thread  
         thread.join();  
         System.out.println("线程退出!");  
     }  
 }  

2,使用stop方法终止,thread.stop();危险慎用

3,使用interrupt方法终止线程 若处于阻塞状态,比如使用了sleep方法,抛出InterruptedException并退出


/** 测试线程的中止与恢复
 *  Thread.interrupted(): 若thread中断,返回true并恢复thread,故再次调用返回false
 *  thread.interrupt() 
 * */
public class ThreadInterrupt extends Thread  
 {  
     public void run()  
     {  
         try 
         {  
             sleep(50000);  // 延迟50秒  
         }  
         catch (InterruptedException e)  
         {  
             System.out.println(e.getMessage()); 
             Thread.interrupted();
             System.out.println("hello");
         }  
         System.out.println("ThreadInterrupt End");
     }  
     public static void main(String[] args) throws Exception  
     {  
         Thread thread = new ThreadInterrupt();  
         thread.start();  
         System.out.println("在50秒之内输入任意字符中断线程!");  
         System.in.read();  
         thread.interrupt();  
         System.out.println(thread.isAlive());
         thread.join();  
         System.out.println("线程已经退出!");  
     }  
 }  

使用interrupt(),线程在正常运行状态指示中止,可以恢复。参考的网址上讲的是错的这里。


/** 证明interrupt只是中断而已,可以恢复,而非结束,
 * 引用网址上讲的的是错的 
 * */
public class TestInterrupt extends Thread{
	public void run(){
		for(long  i =0; i<1000000000; i++){
		}
		System.out.println("thread end");
	}
	
	public static void main(String args[]){
		Thread t=new TestInterrupt();
		t.start();
		System.out.println("before t interrupted");
		t.interrupt();
		System.out.println("after");
		try {
			t.join();
		} catch (InterruptedException e) {
		}
		System.out.println("main end");
	}
}

在Thread类中有两个方法可以判断线程是否通过interrupt方法被终止。一个是静态的方法interrupted(),一个是非静态的方法 isInterrupted(),这两个方法的区别是interrupted用来判断当前线是否被中断,清除中断状态;而isInterrupted可以用来判断其他线程是否被中断,不清除中断状态。

join()方法: 若线程A中调用了B.join(),则A挂起等待B运行完后运行。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。