基础知识
每个正在系统上运行的程序都是一个进程(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里面只允许单一继承,但允许实现多个接口。第二个方法更加灵活。
代码示例
多线程实现1-30的累计,其中共享资源池为1-30的数字的递增,采用了同步锁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 } }
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 } }
客户端:
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 } } }
原文地址:https://www.cnblogs.com/ftl1012/p/9347677.html
时间: 2024-12-29 11:24:12