1. 程式人生 > >Java學習---多線程的學習

Java學習---多線程的學習

col flush .get ble null name lean img 執行

基礎知識

每個正在系統上運行的程序都是一個進程(process)。每個進程包含一到多個線程(thread)。進程也可能是整個程序或者是部分程序的動態執行。

線程是一組指令的集合,或者是程序的特殊段,它可以在程序裏獨立執行。也可以把它理解為代碼運行的上下文。所以線程基本上是輕量級的進程,它負責在單個程序裏執行多任務。

Java對多線程的支持是非常強大的,他屏蔽掉了許多的技術細節,讓我們可以輕松的開發多線程的應用程序。Java裏面有2個方法實現多線程,

1 繼承 Thread類,比如
  class MyThread extends Thread {
    public void run() {
    // 這裏寫上線程的內容
    }
    public static void main(String[] args) {
      // 使用這個方法啟動一個線程
      new MyThread().start();
    }
  }
  2 實現 Runnable接口,例如
  class MyThread implements Runnable{
    public void run() {
    // 這裏寫上線程的內容
    }
    public static void main(String[] args) {
      // 使用這個方法啟動一個線程
      new Thread(new MyThread()).start();
    }
  }
一般鼓勵使用第二種方法,因為Java裏面只允許單一繼承,但允許實現多個接口。第二個方法更加靈活。

代碼示例

多線程實現130的累計,其中共享資源池為130的數字的遞增,采用了同步鎖synchronized

技術分享圖片
 1 class Sum{ //共享資源,計數器count
 2     private int count;//共享資源
 3     public int add(){
 4         synchronized(this){ //代碼段1,共享鎖,修飾程序段或者方法
 5             count = count + 1;
 6             System.out.println("add:" + count);
 7             return count;            
8 } 9 } 10 } 11 class SumThread implements Runnable{//定義線程 12 private Sum sd; 13 private int sum = 0; 14 private int [] a = new int[10]; 15 16 public SumThread(String name, Sum sd){ 17 super(name); 18 this.sd = sd; 19 } 20 public void run(){//必需的重寫
21 try{ 22 for(int i=0;i<10;i++){ 23 a[i] = sd.add(); 24 sum += a[i]; 25 Thread.sleep(100); 26 } 27 Thread.sleep(1000); 28 }catch(Exception e){} 29 30 System.out.println(getName() + "累加和:" + sum); 31 } 32 public void showData(){ 33 System.out.print(getName() + "獲得的數為"); 34 for(int i=0;i<10;i++){ 35 if(i%10==0)System.out.println(); 36 System.out.print(a[i] + "+\t"); 37 } 38 } 39 public int getSum(){ 40 return sum; 41 } 42 } 43 public class SumDemo{ 44 public static void main(String [] args){ 45 Sum sd = new Sum();//代表共享資源的變量 46 SumThread s1 = new SumThread("線程1",sd);//創建完畢 47 SumThread s2 = new SumThread("線程2",sd); 48 SumThread s3 = new SumThread("線程3",sd); 49 Thread st1 = new Thread(s1); 50 Thread st2 = new Thread(s2); 51 Thread st3 = new Thread(s3); 52 st1.setPriority(Thread.MAX_PRIORITY); //代碼段2 53 st2.setPriority(10); 54 st3.setPriority(1); 55 long begin = System.currentTimeMillis(); 56 st1.start();//使線程運行 57 st2.start(); st3.start(); 58 St1.join(); st2.join(); st3.join(); 59 st1.showData(); 60 st2.showData(); 61 st3.showData(); 62 System.out.println("總和為:" + (st1.getSum() + st2.getSum() + st3.getSum())); 63 long end = System.currentTimeMillis(); 64 System.out.println(“探測localhost的TCP端口,共耗時” + 65 ( end - begin)+"毫秒"); 66 } }
View Code

TCP Socket多線程通信

服務端:

技術分享圖片
 1 import java.io.*;
 2 import java.net.*;
 3 import java.util.*;
 4 @SuppressWarnings(value={"deprecation","unchecked"}) //查閱該語句作用
 5 public class MultiServer extends Thread{
 6     ServerSocket serverSocket = null;
 7     boolean listening = true;
 8     int port = 1080;
 9     int count;
10     public MultiServer(){
11         try{
12             serverSocket = new ServerSocket(port);
13             System.out.println("The Chat Server is listening on " + port);
14         }catch(IOException e){
15             System.err.println("Can‘t listen on Port");
16             System.exit(1);
17         }
18         count = 0;
19         while(listening){
20             try{
21                 new ClientServiceThread(serverSocket.accept()).start();
22                 count += 1;
23                 System.out.println("The Chat Server get " + count + " Clients");
24             }catch(IOException e){
25                 System.err.println("Can‘t Accept the Client Connection Apply");
26             }
27         }        
28         try{
29             serverSocket.close();
30         }catch(IOException e){
31             System.exit(1);
32         }
33         this.start();
34     }    
35     public static void main(String args[]){
36         MultiServer ms = new MultiServer();
37 } }
View Code

客戶端:

技術分享圖片
 1 class ClientServiceThread extends Thread{
 2     private String name = "Client";
 3     private Socket socket = null;
 4     private Vector clients = null;
 5     public ClientServiceThread(Socket socket){
 6         super("ClientServiceThread");
 7         this.socket = socket;
 8     }
 9     public ClientServiceThread(Vector clients, Socket socket){
10         super("ClientServiceThread");
11         this.socket = socket;
12         this.clients = clients;
13     }
14     public void run(){
15         try{
16             DataInputStream in = new DataInputStream(new
17           BufferedInputStream(socket.getInputStream()));
18             PrintStream out = new PrintStream(new 
19             BufferedOutputStream(socket.getOutputStream(), 1024), true);
20             
21             String inputLine, outputLine;
22             
23             GreetingProtocol greeting = new GreetingProtocol();
24             outputLine = greeting.processInput(null);
25             
26             out.println("Welcome to My Chat Server,    Please REG your Name, Format: name = yourname");
27             out.flush();
28         
29             while((inputLine = in.readLine()) != null){
30                 System.out.println(this.name + " Say: " + inputLine);
31                 if(inputLine.startsWith("name")){
32                     this.name = 
33 inputLine.substring(inputLine.indexOf("=") + 1);
34                     out.println("Your Name "+ this.name + " is REG");
35                     out.flush();
36                 }else{
37                     outputLine = greeting.processInput(inputLine);
38                     out.println(outputLine);
39                     out.flush();
40                 }
41                 if(inputLine.equals("bye")) break;
42             }
43             out.close();
44             in.close();
45             socket.close();
46         }catch(IOException e){
47             e.printStackTrace();
48 } } }
View Code

Java學習---多線程的學習