溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java實(shí)現(xiàn)的兩個(gè)線程同時(shí)運(yùn)行案例

發(fā)布時(shí)間:2020-08-21 09:08:09 來源:腳本之家 閱讀:107 作者:To哥 欄目:編程語言

本文實(shí)例講述了Java實(shí)現(xiàn)的兩個(gè)線程同時(shí)運(yùn)行。分享給大家供大家參考,具體如下:

/**
 * 兩個(gè)案例同時(shí)運(yùn)行案例
 * 1:這個(gè)兩個(gè)線程并不是有規(guī)律的運(yùn)行而是有沒有規(guī)律的交替運(yùn)行
 */
package com.test3;
public class Demo10_3 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Pig pig=new Pig(10);
        Bird bird=new Bird(10);
        Thread t1=new Thread(pig);
        Thread t2=new Thread(bird);
        t1.start();
        t2.start();
    }
}
//打印
class Pig implements Runnable
{
    int n=0;
    int times=0;
    public Pig(int n)
    {
        this.n=n;
    }
    public void run()
    {
        while(true)
        {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO: handle exception
            }
            times++;
            System.out.println("豬說我是一個(gè)線程,在輸出第"+times+"個(gè)hello, word");
            if(times==n)
            {
                break;
            }
        }
    }
}
//算數(shù)學(xué)
class Bird implements Runnable
{
    int n=0;
    int res=0;
    int times=0;
    public Bird(int n)
    {
        this.n=n;
    }
    public void run()
    {
        while(true)
        {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO: handle exception
            }
            res+=(++times);
            System.out.println("鳥算的當(dāng)前結(jié)果是"+res);
            if(times==n)
            {
                System.out.println("最后結(jié)果是"+res);
                break;
            }
        }
    }
}

運(yùn)行結(jié)果:

Java實(shí)現(xiàn)的兩個(gè)線程同時(shí)運(yùn)行案例

更多java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java進(jìn)程與線程操作技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI