溫馨提示×

溫馨提示×

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

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

怎么在java中利用多線程中執(zhí)行多個程序

發(fā)布時間:2021-02-07 18:21:17 來源:億速云 閱讀:194 作者:Leah 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)怎么在java中利用多線程中執(zhí)行多個程序,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

1、創(chuàng)建線程對象我們需要用到Thread類,該類是java.lang包下的一個類,所以調(diào)用時不需要導(dǎo)入包。下面我們先創(chuàng)建一個新的子類來繼承Thread類,然后通過重寫run()方法(將需要同時進(jìn)行的任務(wù)寫進(jìn)run()方法內(nèi)),來達(dá)到讓程序同時做多件事情的目的。

import java.awt.Graphics;
import java.util.Random;
public class ThreadClass extends Thread{
public Graphics g;
//用構(gòu)造器傳參的辦法將畫布傳入ThreadClass類中
public ThreadClass(Graphics g){
this.g=g;
}
public void run(){
//獲取隨機(jī)的x,y坐標(biāo)作為小球的坐標(biāo)
Random ran=new Random();
int x=ran.nextInt(900);
int y=ran.nextInt(900);
for(int i=0;i<100;i++){
g.fillOval(x+i,y+i,30,30);
try{
Thread.sleep(30);
}catch(Exception ef){
}
}
}
}

2、在主類的按鈕事件監(jiān)聽器這邊插入這樣一段代碼,即每按一次按鈕則生成一個ThreadClass對象。

public void actionPerformed(ActionEvent e){
ThreadClass thc=new ThreadClass(g);
thc.start();
}

3、在這里我們生成ThreadClass對象并調(diào)用start()函數(shù)后,線程被創(chuàng)建并進(jìn)入準(zhǔn)備狀態(tài),每個線程對象都可以同時獨(dú)立執(zhí)行run()方法中的函數(shù),當(dāng)run()方法中的代碼執(zhí)行完畢時線程自動停止。

java8多線程運(yùn)行程序?qū)嵗?/p>

public class Main {
  //method to print numbers from 1 to 10
  public static void printNumbers() {
    for (int i = 1; i <= 10; i++) {
      System.out.print(i + " ");
    }
    //printing new line
    System.out.println();
  }
 
  //main code	
  public static void main(String[] args) {
    //thread object creation
    Thread one = new Thread(Main::printNumbers);
    Thread two = new Thread(Main::printNumbers);
 
    //starting the threads
    one.start();
    two.start();
  }
}

輸出

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

關(guān)于怎么在java中利用多線程中執(zhí)行多個程序就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

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

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

AI