Java如何實現多線程


JAVA里面 ​ JVM(java虛擬機) 就是 一個進程 ​ 進程與進程之間是絕對互相獨立 ​ 我們運行多個main方法,代表有多個JAVA進程 ​ 進程里面有線程; 一個進程里面,允許有多個線程叫多線程;

代碼順序分先后,線程的執行自己跑自己的

  1:繼承Thread

  

 1 public class MyThread extends Thread{
 2     
 3     public void run(){
 4         
 5         //我們這個線程需要實現的功能;要完成任務
 6         
 7     }
 8 }
 9 
10 //1: 新建一個線程對象;
11 //2: 調用start方法;

  

 1 package com.lv.study.pm.second;
 2 
 3 public class Test1 {
 4 
 5     public static void main(String[] args) {
 6 
 7         System.out.println("1:");
 8         
 9         Thread th1=new MyTh();
10         Thread th2=new MyTh();        
11         
12         //沒有啟動線程  只是在主線程里面調用我們的run方法
13         //th1.run();
14         //th2.run();
15         
16         //啟動線程
17         th1.start();
18         th2.start();
19         
20         //線程優先級
21         th2.setPriority(Thread.MAX_PRIORITY);
22         th1.setPriority(Thread.MIN_PRIORITY);
23         
24         System.out.println("2:");
25         
26     }
27 
28 }
29 
30 
31 class MyTh extends Thread{
32     
33     public void run(){
34         
35         //線程的禮讓
36         Thread.yield();
37         
38         for (int i = 0; i < 10; i++) {
39             
40             System.out.println(this.getName()+""+i);
41         }
42     }
43 }

 

  2:實現Runnable

 

  

 1 public class MyRunable implements Runnable{
 2     
 3     public void run(){
 4         
 5         //做我們要做的任務;
 6         
 7     }
 8     
 9 }
10 
11 //1:新建一個MyRunable對象;
12 //2:新建一個Thread對象(MyRunable);
13 //3:通過trhead對象來調用start方法;運行我們的線程;
 1 package com.lv.study.pm.first;
 2 
 3 public class Test2 {
 4 
 5     public static void main(String[] args) {
 6 
 7          //java實現多線程
 8         //1:標准  Runable接口
 9         
10         //接口的實現着
11         Runnable r=new MyRun();
12         
13         
14         //2:接口的使用者  這個使用者沒有實現着代表啥事情也沒有干
15         Thread th=new Thread(r);
16         th.start();//啟動了線程
17         
18     }
19 
20 }
21 
22 
23 //Runnable接口的實現着
24 class MyRun implements Runnable{
25 
26     @Override
27     public void run() {
28 
29         for (int i = 0; i < 10; i++) {
30             
31             System.out.println(i);
32         }
33         
34     }
35     
36 }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM