天天看點

java線程學習1——線程基本概念和操作

一、建立線程的兩種方式

1 繼承runnable接口

public class threadimprunnable implements runnable

{

 /**

  * 線程運作時執行的方法

  */

 public void run()

 {

  for (int i = 0; i < 500; i++)

  {

   system.out.println(thread.currentthread().getname() + i);

  }

 }

}

public class test

  * 主線程,啟動線程必須是start方法

 public static void main(string[] args)

  threadimprunnable tr = new threadimprunnable();

  thread t = new thread(tr);

   t.start();

2 繼承thread類

public class threadextends extends thread

  threadextends tr = new threadextends();

  tr.start();

二、線程的一些方法

1 sleep

public class sleepthread implements runnable

  try

   // 該線程進入阻塞狀态5秒

   thread.sleep(5000);

   for (int i = 0; i < 500; i++)

   {

    system.out.println(thread.currentthread().getname() + i);

   }

  catch (interruptedexception e)

   // 若調用該線程的interrupt方法,會報該異常,真實程式中可以關閉一些資源

   e.printstacktrace();

public class sleeptest

  * 主線程

  sleepthread tr = new sleepthread();

  thread t = new thread(tr);

  t.start();

2 join

public class jointhread implements runnable

  for (int i = 0; i < 100; i++)

public class jointest

  jointhread jt = new jointhread();

  thread t = new thread(jt);

   // 調用該方法将目前線程(此處是主線程)合并到本線程中,執行完本線程,再執行目前線程

   t.join();

3 yield

public class yieldthread extends thread

   if (i % 10 == 0)

    // 當能被10整除時本線程讓出優先級,讓其他線程先執行一會,可看到t1_10下面緊接着t2的結果,同樣t2_20下面緊接着t1的結果

    yield();

public class yieldtest

  yieldthread yt = new yieldthread();

  thread t1 = new thread(yt, "t1_");

  t1.start();

  thread t2 = new thread(yt, "t2_");

  t2.start();

4 setpriority

public class prioritythread extends thread

public class prioritytest

  * 線程優先級預設是5

  int norm = thread.norm_priority; // 5

  int max = thread.max_priority;   // 10

  int min  = thread.min_priority;  // 1

  prioritythread yt = new prioritythread();

  t1.setpriority(norm + 3);