Java多线程。在线程类上同步(此)
我偶然发现了这个关于多客户端-服务器聊天模型的有趣教程。除了一件事,我什么都懂。在类MultiThreadChatServerSync的实现中,他解释说,我们需要同步部分代码,因为不同的线程共享同一资源,即字段Java多线程。在线程类上同步(此),java,multithreading,synchronized,Java,Multithreading,Synchronized,我偶然发现了这个关于多客户端-服务器聊天模型的有趣教程。除了一件事,我什么都懂。在类MultiThreadChatServerSync的实现中,他解释说,我们需要同步部分代码,因为不同的线程共享同一资源,即字段 private final clientThread[] threads; 我读过很多关于同步(这个)工作原理的文章。如果“this”引用线程实例,那么该代码如何同步语句块?假设线程[0]输入一个synchronized(this)语句,以便获得自身的监视器。同时,线程[1]也输入了一
private final clientThread[] threads;
我读过很多关于同步(这个)工作原理的文章。如果“this”引用线程实例,那么该代码如何同步语句块?假设线程[0]输入一个synchronized(this)语句,以便获得自身的监视器。同时,线程[1]也输入了一个synchronized(this)语句,但不会被阻止,因为它将获得自己实例的监视器,而不是线程[0]的监视器。有人能解释一下为什么这个代码是同步的吗?我错过什么了吗
这里是文章的链接。我无法链接到特定部分。所以只需搜索“公共类多线程ChatServerSync”这句话。
以下是无法访问该网页的用户的代码
import java.io.DataInputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.net.Socket;
import java.net.ServerSocket;
/*
* A chat server that delivers public and private messages.
*/
public class MultiThreadChatServerSync {
// The server socket.
private static ServerSocket serverSocket = null;
// The client socket.
private static Socket clientSocket = null;
// This chat server can accept up to maxClientsCount clients' connections.
private static final int maxClientsCount = 10;
private static final clientThread[] threads = new clientThread[maxClientsCount];
public static void main(String args[]) {
// The default port number.
int portNumber = 2222;
if (args.length < 1) {
System.out.println("Usage: java MultiThreadChatServerSync <portNumber>\n" + "Now using port number=" + portNumber);
} else {
portNumber = Integer.valueOf(args[0]).intValue();
}
/*
* Open a server socket on the portNumber (default 2222). Note that we can
* not choose a port less than 1023 if we are not privileged users (root).
*/
try {
serverSocket = new ServerSocket(portNumber);
} catch (IOException e) {
System.out.println(e);
}
/*
* Create a client socket for each connection and pass it to a new client
* thread.
*/
while (true) {
try {
clientSocket = serverSocket.accept();
int i = 0;
for (i = 0; i < maxClientsCount; i++) {
if (threads[i] == null) {
(threads[i] = new clientThread(clientSocket, threads)).start();
break;
}
}
if (i == maxClientsCount) {
PrintStream os = new PrintStream(clientSocket.getOutputStream());
os.println("Server too busy. Try later.");
os.close();
clientSocket.close();
}
} catch (IOException e) {
System.out.println(e);
}
}
}
}
/*
* The chat client thread. This client thread opens the input and the output
* streams for a particular client, ask the client's name, informs all the
* clients connected to the server about the fact that a new client has joined
* the chat room, and as long as it receive data, echos that data back to all
* other clients. The thread broadcast the incoming messages to all clients and
* routes the private message to the particular client. When a client leaves the
* chat room this thread informs also all the clients about that and terminates.
*/
class clientThread extends Thread {
private String clientName = null;
private DataInputStream is = null;
private PrintStream os = null;
private Socket clientSocket = null;
private final clientThread[] threads;
private int maxClientsCount;
public clientThread(Socket clientSocket, clientThread[] threads) {
this.clientSocket = clientSocket;
this.threads = threads;
maxClientsCount = threads.length;
}
public void run() {
int maxClientsCount = this.maxClientsCount;
clientThread[] threads = this.threads;
try {
/*
* Create input and output streams for this client.
*/
is = new DataInputStream(clientSocket.getInputStream());
os = new PrintStream(clientSocket.getOutputStream());
String name;
while (true) {
os.println("Enter your name.");
name = is.readLine().trim();
if (name.indexOf('@') == -1) {
break;
} else {
os.println("The name should not contain '@' character.");
}
}
/* Welcome the new the client. */
os.println("Welcome " + name
+ " to our chat room.\nTo leave enter /quit in a new line.");
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] == this) {
clientName = "@" + name;
break;
}
}
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this) {
threads[i].os.println("*** A new user " + name + " entered the chat room !!! ***");
}
}
}
/* Start the conversation. */
while (true) {
String line = is.readLine();
if (line.startsWith("/quit")) {
break;
}
/* If the message is private sent it to the given client. */
if (line.startsWith("@")) {
String[] words = line.split("\\s", 2);
if (words.length > 1 && words[1] != null) {
words[1] = words[1].trim();
if (!words[1].isEmpty()) {
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this
&& threads[i].clientName != null
&& threads[i].clientName.equals(words[0])) {
threads[i].os.println("<" + name + "> " + words[1]);
/*
* Echo this message to let the client know the private
* message was sent.
*/
this.os.println(">" + name + "> " + words[1]);
break;
}
}
}
}
}
} else {
/* The message is public, broadcast it to all other clients. */
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i].clientName != null) {
threads[i].os.println("<" + name + "> " + line);
}
}
}
}
}
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] != null && threads[i] != this && threads[i].clientName != null) {
threads[i].os.println("*** The user " + name + " is leaving the chat room !!! ***");
}
}
}
os.println("*** Bye " + name + " ***");
/*
* Clean up. Set the current thread variable to null so that a new client
* could be accepted by the server.
*/
synchronized (this) {
for (int i = 0; i < maxClientsCount; i++) {
if (threads[i] == this) {
threads[i] = null;
}
}
}
/*
* Close the output stream, close the input stream, close the socket.
*/
is.close();
os.close();
clientSocket.close();
} catch (IOException e) {
}
}
}
import java.io.DataInputStream;
导入java.io.PrintStream;
导入java.io.IOException;
导入java.net.Socket;
导入java.net.ServerSocket;
/*
*提供公共和私人消息的聊天服务器。
*/
公共类多线程ChatServerSync{
//服务器套接字。
私有静态ServerSocket ServerSocket=null;
//客户端套接字。
私有静态套接字clientSocket=null;
//此聊天服务器最多可以接受maxClientsCount客户端的连接。
私有静态final int MaxClientScont=10;
私有静态最终clientThread[]线程=新clientThread[MaxClientScont];
公共静态void main(字符串参数[]){
//默认端口号。
int端口号=2222;
如果(参数长度<1){
System.out.println(“用法:java多线程ChatServerSync\n”+”现在使用端口号=“+portNumber”);
}否则{
portNumber=Integer.valueOf(args[0]).intValue();
}
/*
*打开端口号上的服务器套接字(默认2222)。请注意,我们可以
*如果我们不是特权用户(root),请不要选择小于1023的端口。
*/
试一试{
serverSocket=新的serverSocket(端口号);
}捕获(IOE异常){
系统输出打印ln(e);
}
/*
*为每个连接创建一个客户端套接字,并将其传递给新的客户端
*线。
*/
while(true){
试一试{
clientSocket=serverSocket.accept();
int i=0;
对于(i=0;i1&&words[1]!=null){
单词[1]=单词[1]。trim();
如果(!words[1].isEmpty()){
已同步(此){
对于(int i=0;i