多線程1-線程和進程的實現

線程與進程

  1. 線程:程序中單獨順序的控制流
    線程本身依靠程序進行運行
    線程是程序中的順序控制流,只能使用分配給程序的資源和環境

  2. 進程:執行中的程序
    一個進程可以包含一個或多個線程
    一個進程至少要包含一個線程

  3. 單線程:
    程序中只存在一個線程,實際上主方法就是一個主線程
  4. 多線程:
    多線程是在程序中運行多個任務
    多線程的目的是更好的使用CPU資源

線程的實現

1.在Java中,線程的實現有兩種:
繼承Thread類
實現Runnable接口

//繼承Thread類
public class MyThread extends Thread{
    public void run(){
        for(int i=1;i<=100;i++){
            System.out.println("run:"+i);
        }
    }

    //main方法
    public static void main(String[] args){
        MyThread t1=new MyThread();
        t1.start();
    }
}
//實現runnable接口
public class MyRunnable implements Runnable{
    private String name;
    public MyRunable(String name){
        this.name=name;
    }
    public void run(){
        for(int i=1;i<=100;i++){
            System.out.println(name+":"+i);
        }
    }

    //main方法
    public static void main(String[] args){
        MyRunnable r1=new MyRunnable("A");
        MyRunnable r2=new MyRunnable("B");
        Thread t1=new Thread(r1);
        Thread t2=new Thread(r2);
        t1.start();
        t2.start();
    }
}
發佈了58 篇原創文章 · 獲贊 25 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章