多線程基礎(chǔ)1:創(chuàng)建線程的三種方式

前言

創(chuàng)建線程有三種方式:

1.繼承Thread

  1. 實現(xiàn)Runnable
  2. 實現(xiàn)Callable

具體代碼

1.繼承Thread:繼承這種方式不推薦用,因為繼承Thread之后便不能繼承其他類,導(dǎo)致很局限

    public void run(){//線程入口點
        for(int i=0;i<20;i++)
        System.out.println("啦啦啦");
    }
    public static void main(String[] args) {
        Thread01 st=new Thread01();
        st.start();//不一定立刻運行。由cpu決定
        for(int i=0;i<20;i++)
            System.out.println("插隊插隊");

    }
}

2.實現(xiàn)Runnable:推薦使用方式

    public void run(){//線程入口點
        for(int i=0;i<20;i++)
            System.out.println("啦啦啦");
    }
    public static void main(String[] args) {
        Thread01 st=new Thread01();
        Thread t=new Thread(st);//代理類對象
        t.start();//不一定立刻運行。由cpu決定
        for(int i=0;i<20;i++)
            System.out.println("插隊插隊");

    }
}

用第二種方式模仿?lián)屍焙妄斖觅惻埽?/p>

搶票:(此處并發(fā)問題將在后期的文章講解)


package thread;

public class Ticket_garbbing implements Runnable{
    private int tickrtSize=100;
    @Override
    public void run() {
        while(true) {
            if (tickrtSize < 0) {
                break;
            }
            try {
                Thread.sleep(200);//模仿網(wǎng)絡(luò)延時此時出現(xiàn)負數(shù)出現(xiàn)并發(fā)問題
            } catch (InterruptedException e) {//并發(fā)需要保證線程安全
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"/"+tickrtSize--);
        }
    }

    public static void main(String[] args) {
        Ticket_garbbing tg1=new Ticket_garbbing();

        new Thread(tg1,"io1").start();
        new Thread(tg1,"io2").start();
        new Thread(tg1,"io3").start();
        new Thread(tg1,"io4").start();
        new Thread(tg1,"io5").start();
        new Thread(tg1,"io6").start();
    }
}

龜兔賽跑:


package thread;
/*
* 龜兔賽跑
* */
public class Racter implements Runnable{
    //勝利者
    private static String winner;
    @Override
    public void run() {
       //假設(shè)賽道長100米兔子每過10s睡一次覺
       for(int i=0;i<=100;i++){
           if(i%10==0&&Thread.currentThread().getName().equals("rabbit")){
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
           System.out.println(Thread.currentThread().getName()+"-->"+i);
           boolean flag=gameOver(i);
           if(flag){
               System.out.println("winner is "+winner);
               break;

           }
       }
    }
    //判斷是否到達終點
    private boolean gameOver(int i){
        if(winner!=null){
            return true;
        }else{
            if(i==100){
               winner=Thread.currentThread().getName();
               return true;
            }else {
                return false;
            }
        }
    }

    public static void main(String[] args) {
        Racter racter=new Racter();
        new Thread(racter,"rabbit").start();
        new Thread(racter,"tortoise").start();

    }
}

實現(xiàn)Callable(一般實際開發(fā)中使用的方式)



import java.util.concurrent.*;

public class NewClassable implements Callable<Boolean> {
    private  String path;
    public  NewClassable(String path){
        this.path=path;
    }
    @Override
    public Boolean call() throws Exception {
        System.out.println(path);
      down();
        return true;
    }
    private void down(){
        System.out.println("圖片下載");
    }
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NewClassable n1=new NewClassable("a");
        NewClassable n2=new NewClassable("b");
        NewClassable n3=new NewClassable("c");
        //創(chuàng)建執(zhí)行任務(wù)
        ExecutorService service= Executors.newFixedThreadPool(3);
        //提交服務(wù)
        Future<Boolean> rt1=service.submit(n1);
        Future<Boolean> rt2=service.submit(n2);
        Future<Boolean> rt3=service.submit(n3);
        //獲取結(jié)果
        boolean r1=rt1.get();
        boolean r2=rt2.get();
        boolean r3=rt3.get();
        //關(guān)閉服務(wù)
        service.shutdownNow();
    }
}

此文章來至個人視頻資料整理,請多指教.

作者:欲指_Object
來源:CSDN
原文:https://blog.csdn.net/apple596529/article/details/89449905
版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請附上博文鏈接!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容