java多線程中執(zhí)行多個(gè)程序的實(shí)例分析
我們知道多線程因?yàn)橥瑫r(shí)處理子線程的能力,對于程序運(yùn)行來說,能夠達(dá)到很高的效率。不過很多人對于多線程的執(zhí)行方法還沒有嘗試過,本篇我們將為大家介紹創(chuàng)建線程的方法,在這個(gè)基礎(chǔ)上,對程序執(zhí)行多條命令的方法進(jìn)行展示。下面我們就來看看具體的操作步驟吧。
1、創(chuàng)建線程對象我們需要用到Thread類,該類是java.lang包下的一個(gè)類,所以調(diào)用時(shí)不需要導(dǎo)入包。下面我們先創(chuàng)建一個(gè)新的子類來繼承Thread類,然后通過重寫run()方法(將需要同時(shí)進(jìn)行的任務(wù)寫進(jìn)run()方法內(nèi)),來達(dá)到讓程序同時(shí)做多件事情的目的。
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)聽器這邊插入這樣一段代碼,即每按一次按鈕則生成一個(gè)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),每個(gè)線程對象都可以同時(shí)獨(dú)立執(zhí)行run()方法中的函數(shù),當(dāng)run()方法中的代碼執(zhí)行完畢時(shí)線程自動(dòng)停止。
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 101 2 3 4 5 6 7 8 9 10
到此這篇關(guān)于java多線程中執(zhí)行多個(gè)程序的實(shí)例分析的文章就介紹到這了,更多相關(guān)java多線程中執(zhí)行多個(gè)程序內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. php5.6不能擴(kuò)展redis.so的解決方法2. python中的列表和元組區(qū)別分析3. python代碼如何注釋4. 微信開發(fā) 網(wǎng)頁授權(quán)獲取用戶基本信息5. css列表標(biāo)簽list與表格標(biāo)簽table詳解6. jsp session.setAttribute()和session.getAttribute()用法案例詳解7. python 實(shí)現(xiàn)彈球游戲的示例代碼8. .Net 7函數(shù)Ctor與CCtor使用及區(qū)別詳解9. Spring獲取ApplicationContext對象工具類的實(shí)現(xiàn)方法10. Ajax實(shí)現(xiàn)頁面無刷新留言效果
