首页 技术 正文
技术 2022年11月15日
0 收藏 928 点赞 4,329 浏览 3955 个字

基础知识

每个正在系统上运行的程序都是一个进程(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。

 class Sum{ //共享资源,计数器count
private int count;//共享资源
public int add(){
synchronized(this){ //代码段1,共享锁,修饰程序段或者方法
count = count + 1;
System.out.println("add:" + count);
return count;
}
}
}
class SumThread implements Runnable{//定义线程
private Sum sd;
private int sum = 0;
private int [] a = new int[10]; public SumThread(String name, Sum sd){
super(name);
this.sd = sd;
}
public void run(){//必需的重写
try{
for(int i=0;i<10;i++){
a[i] = sd.add();
sum += a[i];
Thread.sleep(100);
}
Thread.sleep(1000);
}catch(Exception e){} System.out.println(getName() + "累加和:" + sum);
}
public void showData(){
System.out.print(getName() + "获得的数为");
for(int i=0;i<10;i++){
if(i%10==0)System.out.println();
System.out.print(a[i] + "+\t");
}
}
public int getSum(){
return sum;
}
}
public class SumDemo{
public static void main(String [] args){
Sum sd = new Sum();//代表共享资源的变量
SumThread s1 = new SumThread("线程1",sd);//创建完毕
SumThread s2 = new SumThread("线程2",sd);
SumThread s3 = new SumThread("线程3",sd);
Thread st1 = new Thread(s1);
Thread st2 = new Thread(s2);
Thread st3 = new Thread(s3);
st1.setPriority(Thread.MAX_PRIORITY); //代码段2
st2.setPriority(10);
st3.setPriority(1);
long begin = System.currentTimeMillis();
st1.start();//使线程运行
st2.start(); st3.start();
St1.join(); st2.join(); st3.join();
st1.showData();
st2.showData();
st3.showData();
System.out.println("总和为:" + (st1.getSum() + st2.getSum() + st3.getSum()));
long end = System.currentTimeMillis();
System.out.println(“探测localhost的TCP端口,共耗时” +
( end - begin)+"毫秒");
} }

TCP Socket多线程通信

服务端:

 import java.io.*;
import java.net.*;
import java.util.*;
@SuppressWarnings(value={"deprecation","unchecked"}) //查阅该语句作用
public class MultiServer extends Thread{
ServerSocket serverSocket = null;
boolean listening = true;
int port = 1080;
int count;
public MultiServer(){
try{
serverSocket = new ServerSocket(port);
System.out.println("The Chat Server is listening on " + port);
}catch(IOException e){
System.err.println("Can't listen on Port");
System.exit(1);
}
count = 0;
while(listening){
try{
new ClientServiceThread(serverSocket.accept()).start();
count += 1;
System.out.println("The Chat Server get " + count + " Clients");
}catch(IOException e){
System.err.println("Can't Accept the Client Connection Apply");
}
}
try{
serverSocket.close();
}catch(IOException e){
System.exit(1);
}
this.start();
}
public static void main(String args[]){
MultiServer ms = new MultiServer();
} }

客户端:

 class ClientServiceThread extends Thread{
private String name = "Client";
private Socket socket = null;
private Vector clients = null;
public ClientServiceThread(Socket socket){
super("ClientServiceThread");
this.socket = socket;
}
public ClientServiceThread(Vector clients, Socket socket){
super("ClientServiceThread");
this.socket = socket;
this.clients = clients;
}
public void run(){
try{
DataInputStream in = new DataInputStream(new
BufferedInputStream(socket.getInputStream()));
PrintStream out = new PrintStream(new
BufferedOutputStream(socket.getOutputStream(), 1024), true); String inputLine, outputLine; GreetingProtocol greeting = new GreetingProtocol();
outputLine = greeting.processInput(null); out.println("Welcome to My Chat Server, Please REG your Name, Format: name = yourname");
out.flush(); while((inputLine = in.readLine()) != null){
System.out.println(this.name + " Say: " + inputLine);
if(inputLine.startsWith("name")){
this.name =
inputLine.substring(inputLine.indexOf("=") + 1);
out.println("Your Name "+ this.name + " is REG");
out.flush();
}else{
outputLine = greeting.processInput(inputLine);
out.println(outputLine);
out.flush();
}
if(inputLine.equals("bye")) break;
}
out.close();
in.close();
socket.close();
}catch(IOException e){
e.printStackTrace();
} } }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,484
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,899
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,732
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,485
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,125
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,286