我們知道多線程因為同時處理子線程的能力,對于程序運行來說,能夠達到很高的效率。不過很多人對于多線程的執行方法還沒有嘗試過,本篇我們將為大家介紹創建線程的方法,在這個基礎上,對程序執行多條命令的方法進行展示。下面我們就來看看具體的操作步驟吧。
1、創建線程對象我們需要用到Thread類,該類是java.lang包下的一個類,所以調用時不需要導入包。下面我們先創建一個新的子類來繼承Thread類,然后通過重寫run()方法(將需要同時進行的任務寫進run()方法內),來達到讓程序同時做多件事情的目的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
import java.awt.Graphics; import java.util.Random; public class ThreadClass extends Thread{ public Graphics g; //用構造器傳參的辦法將畫布傳入ThreadClass類中 public ThreadClass(Graphics g){ this .g=g; } public void run(){ //獲取隨機的x,y坐標作為小球的坐標 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、在主類的按鈕事件監聽器這邊插入這樣一段代碼,即每按一次按鈕則生成一個ThreadClass對象。
1
2
3
4
|
public void actionPerformed(ActionEvent e){ ThreadClass thc= new ThreadClass(g); thc.start(); } |
3、在這里我們生成ThreadClass對象并調用start()函數后,線程被創建并進入準備狀態,每個線程對象都可以同時獨立執行run()方法中的函數,當run()方法中的代碼執行完畢時線程自動停止。
java8多線程運行程序實例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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
到此這篇關于java多線程中執行多個程序的實例分析的文章就介紹到這了,更多相關java多線程中執行多個程序內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/java/jichu/23710.html