Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2026096
  • 博文数量: 413
  • 博客积分: 10926
  • 博客等级: 上将
  • 技术积分: 3862
  • 用 户 组: 普通用户
  • 注册时间: 2006-01-09 18:14
文章分类

全部博文(413)

文章存档

2015年(5)

2014年(1)

2013年(5)

2012年(6)

2011年(138)

2010年(85)

2009年(42)

2008年(46)

2007年(26)

2006年(59)

分类: Java

2010-09-10 11:45:02

  1. Documents
    • Reference
      http://cupi2.uniandes.edu.co/site/images/recursos/javadoc/j2se/1.5.0/docs/api/java/lang/Thread.html
    • Samples
      • http://walsh.javaeye.com/blog/220212
      • http://www.ctba.cn/blog/entry/1475
    • xxx
  2. Thread Types
    • Use Thread
      class MyThread extends Thread
      {
          private int m_keeps;
          public MyThread(int keeps)
          {
              m_keeps = keeps;
         }

         public void run()
          {
              while(true)
              {  
               try
                  {
                   System.out.println(":" + new Date(System.currentTimeMillis()));
                   Thread.sleep(pauseTime);
                }
                  catch(Exception e)
                  {
                  System.out.println(e);
               }
              }
          }

        static public void main(String args[])
         {
              MyThread thread = new MyThread(10000);
            thread.start();
        }
      }
    • Use Runnable
      class MyRunnable extends Runnable
      {
          private int m_keeps;
          public MyRunnable(int keeps)
          {
              m_keeps = keeps;
         }

         public void run()
          {
              while(true)
              {  
               try
                  {
                   System.out.println(":" + new Date(System.currentTimeMillis()));
                   Thread.sleep(pauseTime);
                }
                  catch(Exception e)
                  {
                  System.out.println(e);
               }
              }
          }

        static public void main(String args[])
         {
              Thread thread = new Thread(new MyRunnable(10000));
            thread.start();
        }
      }
    • Timer + TimerTask
      public class TimerTaskS extends TimerTask{
                     public TimerTaskS(){
                           //constructor
                     }
                     public void run(){
                          //run code entity
               }
            }

      任务调用:

      Timer timer = new Timer();

      //3秒钟后执行任务

      timer.schedule(new TimerTaskS(),3000);

      //3秒钟后执行任务并且之后每5秒钟执行一次

      timer.schedule(new TimerTaskS(),3000,5000);
  3. Thread Communication
    • Send messages from addition thread: Thread/Runnable + Handler + Message. ie:
      public class MyClass
      {
          private MyThread extends Thread
          {
              private Handler m_handler;
             
              public MyThread (Handler handler)
              {
                  m_handler = handler;
              }


              public void run()
              {
                  int i = 0;

                  while (true)
                  {
                      try
                      {
                          sendMessage(++i);
                          Thread.sleep(2000);
                      }
                      catch (Exception e)
                      {
                       System.out.println(e);
                      }
                  }
              }

              public void sendMessage(String data)
              {
                  Message msg = m_handler.obtainMessage();
                  msg.what = xxx;
                  msg.obj = data;
                  msg.sendToTarget();
              }
          }


          private class MyHandler extends Handler
          {
              public void handleMessage(Message msg)
              {
                  switch (msg.what)
                  {
                  case xxx:
                      xxx
                      break;
                  case xxx:
                      break;
                  default:
                      break;
                  }
              }
          }


          public void myFunc(xxxx)
          {
              ......
              ......
              //The handler is running in main thread;
              MyThread thread = new MyThread(new MyHandler());
              thread.start();
          }
      }
    • Send messages to addition thread: HandlerThread + Handler + Message (Sample: Android source code IntentService.java), or Thread + Looper + Handler + Message; in fact, HandlerThread is implemented with Thread + Looper, please refer to HandlerThread.java. ie:
      public class MyClass
      {
          private class MyHandler extends Handler
          {
              public void handleMessage(Message msg)
              {
                  switch (msg.what)
                  {
                  case xxx:
                      xxx
                      break;
                  case xxx:
                      break;
                  case EXIT:
                      getLooper.quit();
                      break;
                  default:
                      break;
                  }
              }
          }


          public void myFunc(xxxx)
          {
              ......
              ......
              HandlerThread thread = new HandlerThread("xxxx");
              thread.start();
              
              Looper threadLooper = thread.getLooper();

              //The handler is running in addition thread; you can send message from main thread to the addition thread.
              //You must sent EXIT message, or call threadLooper.quit() to terminate the addition thread once it is no longer used.


              Handler handleMessage = new Handler(threadLooper);
          }
      }
  4. Thread Synchronize
    • Synchronized
      • 2 synchronzied types
        Block whole method:
             synchronized somemethod()  //synchronized method
             {
                  ......
             }

        Block statements:
             somemethod()
             {
                  ......
                  synchronized (sync_obj)
                  {
                       //synchronized code
                  }
                  ......
             }
      • Notes:
        1. If a thread has got a lock, then it requests to get the lock again, the second request will not be blocked. So, the following code snip will not cause dead-lock;
          A) Sample A
          synchronized funcA()
          {
              funcA_back();
          }

          synchronized funcA_back()
          {
          }

          B) Sample B
          Object SYNC_OBJ_A = new Object();
          Object SYNC_OBJ_B = new Object();
          funcB()
          {
              synchronized(SYNC_OBJ_A)
              {
                   synchronized(SYNC_OBJ_B)
                   {
                       funcB_back
                   }
              }
          }

          funcB_back()
          {
              synchronized(SYNC_OBJ_B)
              {
                   synchronized(SYNC_OBJ_A)
                   {
                   }
              }
          }

        2. synchronized method is locked on the class object, just as to use 'synchronize (this)' for the whole method body. That meas
          synchronized type getValue()
          {
              return value;
          }

          synchronized void setValue(type value)
          {
              this.value = value;
          }

          void setValue_S(type value)
          {
              synchronized (this)
              {
                  this.value = value;
              }
          }

          when getValue is invoked, setValue will be blocked, and the statements to reset value field in method setValue_S will be blocked also.

        3. The key 'this' can be use as synchronized object, such as
          synchronized (this)
          {
              ...... // synchronzied statements
          }
        4. Construct method need not be synchonized, since it is create only in a single thread. But if you need to synchnozed some statements in construct, you can do like this:
          MyClass()
          {
              public void myMethod ()
              {
                  synchronized (MyClass.class)
                  {
                      num++;
                  }
              }
          }
        5. Synchronized in static method
          MyClass()
          {
              public void myMethod ()
              {
                  synchronized (MyClass.class)
                  {
                      num++;
                  }
              }
          }
        6. xxx
      • Warning
        1. Don't use String literals for the synchronized blocks! such as:

          private final String _lock = "LOCK";
          ...
          synchronized(_lock)
          {
          ...
          }

          Reason:
          Recall section 3.10.5 of the Java Language Spec 2.0:
          It says among other things:
          "Literal strings within different classes in different packages likewise represent references to the same String object.", that means:
          1. Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).
          2. Literal strings within different classes in the same package represent references to the same String object.
          3. Literal strings within different classes in different packages likewise represent references to the same String object.
          4. Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
          5. Strings computed at run time are newly created and therefore distinct.
          6. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

          Solution:
          If you really need an object for locking purposes, just create a new Object() to lock on. Also consider various alternatives, namely using this or facilities in the java.util.concurrent package.

          Ref:

        2. xxx
      • xxx
    • wait, notify/notifyAll

      synchronized (this)
      {
          while (!cond) wait();
      }


      synchronized (this)
      {
          ......
          cond = true;
          notify()/notifyAll();
      }

      Note:
      wait and notify/notifyAll themself must be synchronzied.
    • xxx
  5. Thread States
    1. Classes
      • Thread.State
    2. Refer:
      - Java编程体验:线程的7种状态及相互转换
          
      - Java线程:线程状态的转换
         http://lavasoft.blog.51cto.com/62575/99153/
      - Java 线程的状态与控制
        
      - Java线程的6种状态
        
       
      States: New, Runnable, Runing, Terminated, Blocked/Waiting/Waiting_Time

      NEW: 至今尚未启动的线程处于这种状态。
      RUNNABLE: 正在 Java 虚拟机中执行的线程处于这种状态。处于可运行状态的某一线程正在 Java 虚拟机中运行,但它可能正在等待操作系统中的其他资源,比如处理器。
      [RUNNING: 线程正在运行,当时间片用完或者线程主动调用yield时,进入RUNNABLE状态 (RUNNABLE:线程在JVM调度池中等待被选中,选中后进入RUNNING状态)]
      BLOCKED: 受阻塞并且正在等待监视器锁的某一线程的线程状态。处于受阻塞状态的某一线程正在等待进入synchronized 方法或代码块。
      WAITING: 无限期地等待另一个线程来执行某一特定操作的线程处于这种状态。某一线程因为调用下列方法之一而处于等待状态:
          1、不带超时值的 Object.wait
          2、不带超时值的 Thread.join
          3、LockSupport.park

      处于等待状态的线程正等待另一个线程,以执行特定操作。 例如,已经在某一对象上调用了 Object.wait() 的线程正等待另一个线程,以便在该对象上调用 Object.notify() 或 Object.notifyAll()。已经调用了 Thread.join() 的线程正在等待指定线程终止。

      TIMED_WAITING: 具有指定等待时间的某一等待线程的线程状态。某一线程因为调用以下带有指定正等待时间的方法之一而处于定时等待状态:
          1、Thread.sleep
          2、带有超时值的 Object.wait
          3、带有超时值的 Thread.join
          4、LockSupport.parkNanos
          5、LockSupport.parkUntil
      TERMINATED: 已终止线程的线程状态。线程run已经执行完成。


      (The following diagram is from web site, it is not accurate when to describe the way to enter Blocked/Waiting/Waiting_times state, but it is still useful)

  6. Notes:
    • For some platform, you CANNOT modity ui elements directly in thread since the ui APIs may be not thread-safe, such as on Android
    • Why thread discard stop() and suspend()
      Since they are not safe. stop() causes all lock unlocked immediately, so the protected objects may become destroyed; while suspend() is invoked, all lock still keep locked, so it will lead to dead-lock. More details, plrease refer to <> 1.5.12
    • xxx
  7. xxx
阅读(853) | 评论(0) | 转发(0) |
0

上一篇:[Android] TabActivity

下一篇:[Android] Thread

给主人留下些什么吧!~~