天天看點

線程的概念

什麼是程序?

程序是程式的一次動态執行過程,它是從代碼加載、代碼執行到執行完畢的一個完整的過程

同一段程式,可以作為執行藍本被多次加載到系統的不同記憶體區域中執行,進而形成不同的程序

什麼是線程?

線程是比程序更小的機關,可以是程序的一部分。一個程序在其執行過程中,可以産生多個線程,形成多個執行流。

TestNoneThread.java

class Living
{
 public static void work()
   { for(int i=0; i<10; i++)
   { 
   System.out.print("工作 "); 
   } 
   System.out.println(); }
    public static void rest() {
     for (int i=0; i<10; i++) 
     { 
     System.out.print("休息 ");
      } 
     System.out.println();
      }
}
public class TestNoneThread
{
 public static void main(String[ ] args)
 {
 //不能達到工作和休息交替進行的任務
 Living.work();
 Living.rest();
 }
}      

運作結果:

線程的概念

TestWithThread.java

class Living{
 public static void work(){
 for(int i=0; i<10; i++){
 System.out.print("工作 ");
 try{ Thread.sleep(100); }
 catch(InterruptedException e){}
 }
 }
 public static void rest(){
 for (int i=0; i<10; i++){
 System.out.print("休息 ");
 try{ Thread.sleep(100); }
 catch(InterruptedException e){}
 }
 }
}
class WorkThread extends Thread
{
 public void run()
 {
 Living.work();
 }
}
class RestThread extends Thread
{
 public void run() {
 Living.rest();
 }
}
public class TestWithThread
{
 public static void main(String[] args)
 {
 //能達到工作和休息交替進行的任務
 WorkThread workThread = new WorkThread();
 RestThread restThread = new RestThread();
 workThread.start();
 restThread.start();
 }
}
workThread.start();
restThread.start();      
線程的概念