1、两个线程加两个线程减
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
两个线程加两个线程减
*/
public class ThreadTest3 {
private static int j;
private static final Lock lock = new ReentrantLock();
public static void main(String[] args) {
for (int i = 0; i < 2; i++){
new Thread(new Runnable() {
public void run() {
while (true) {
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"j--=" + j--);
} finally {
lock.unlock();
}
}
}
}).start();
new Thread(new Runnable() {
public void run() {
while (true) {
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"j++=" + j++);
} finally {
lock.unlock();
}
}
}
}).start();
}
}
}
2、子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次
package com.zhang.thread;
/**
* @author zhangjinru
*子线程循环10次,接着主线程循环100,接着又回到子线程循环10次,接着再回到主线程又循环100,如此循环50次
*/
public class ThreadTest2 {
public static void main(String[] args) {
new ThreadTest2().init();
}
public void init() {
Business business = new Business();
new Thread(new Runnable() {
public void run() {
for (int i = 1; i <= 50; i++) {
business.SubThread(i);
}
}
}).start();
for (int i = 1; i <= 50; i++) {
business.MainThread(i);
}
}
private class Business {
boolean bShouldSub = true;// 这里相当于定义了控制该谁执行的一个信号灯
public synchronized void MainThread(int i) {
if (bShouldSub)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100; j++) {
System.out.println(Thread.currentThread().getName() + ":第" + i + "次,j=" + j);
}
bShouldSub = true;
this.notify();
}
public synchronized void SubThread(int i) {
if (!bShouldSub)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread().getName() + ":第" + i + "次,j=" + j);
}
bShouldSub = false;
this.notify();
}
}
}
网络上具有唯一标识的IP地址和端口组合在一起才能构成唯一能识别的标识符套接字。
Socket原理机制:
通信的两端都有Socket
网络通信其实就是Socket间的通信
数据在两个Socket间通过IO传输
客户端编写:
创建一个Socket实例:构造函数向指定的远程主机和端口建立一个TCP连接;
通过套接字的I/O流与服务端通信;
使用Socket类的close方法关闭连接。
public class ClientSocket { public static void main(String args[]) { String host = "127.0.0.1"; int port = 8919; try { Socket client = new Socket(host, port); Writer writer = new OutputStreamWriter(client.getOutputStream()); writer.write("Hello From Client"); writer.flush(); writer.close(); client.close(); } catch (IOException e) { e.printStackTrace(); } } }
上面代码中,host即客户端需要连接的机器,port就是服务器端用来监听请求的端口。在选择端口时,需要注意一点,就是0~1023这些端口都已经被系统预留了。这些端口为一些常用的服务所使用,比如邮件,FTP和HTTP。当你在编写服务器端的代码,选择端口时,请选择一个大于1023的端口。
服务器端编写:
创建一个ServerSocket实例并指定本地端口,用来监听客户端在该端口发送的TCP连接请求;
重复执行:
-
调用ServerSocket的accept()方法以获取客户端连接,并通过其返回值创建一个Socket实例;
-
为返回的Socket实例开启新的线程,并使用返回的Socket实例的I/O流与客户端通信;
-
通信完成后,使用Socket类的close()方法关闭该客户端的套接字连接。
public class ServerClient { public static void main(String[] args) { int port = 8919; try { ServerSocket server = new ServerSocket(port); while(true){ Socket socket = server.accept(); Reader reader = new InputStreamReader(socket.getInputStream()); char chars[] = new char[1024]; int len; StringBuilder builder = new StringBuilder(); while ((len=reader.read(chars)) != -1) { builder.append(new String(chars, 0, len)); } System.out.println("Receive from client message=: " + builder); } reader.close(); socket.close(); server.close(); } catch (Exception e) { e.printStackTrace(); } } }
上面的代码创建了一个服务器端的socket,然后调用accept方法监听并获取客户端的请求socket。accept方法是一个阻塞方法,在服务器端与客户端之间建立联系之前会一直等待阻塞。
5、简单的Socket通讯(面试)
客户端:
package com.zhang.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
//没有关闭流
public class test1 {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
try {
Thread.sleep(5000);
dataOutputStream.writeUTF("哈哈哈");
dataOutputStream.flush();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
while (true) {
String str = dataInputStream.readUTF();
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
服务端:
package com.zhang.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
//没有关闭流
public class test2 {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
System.out.println("等待连接");
Socket socket = serverSocket.accept();
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
new Thread(new Runnable() {
public void run() {
try {
while (true) {
String str = dataInputStream.readUTF();
System.out.println(str);
dataOutputStream.writeUTF("客户端发来的:" + str);// 读出了后再写回去
dataOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
6、Socket的多人聊天室
客户端:
package com.zhang.socket;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
public class ChatClient extends Frame {
private static final long serialVersionUID = 1L;
private TextArea ta = new TextArea();
private TextField tf = new TextField();
private DataOutputStream dos = null;
private DataInputStream dis = null;
private Socket socket = null;
private boolean bConnected = false;
private Thread thread = null;
public static void main(String[] args) {
new ChatClient().frameClient();
}
public void frameClient() {
setSize(400, 400);
setLocation(400, 300);
add(ta, BorderLayout.NORTH);
add(tf, BorderLayout.SOUTH);
pack();//Frame 布局
tf.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String strMsg = tf.getText();
tf.setText("");
try {
dos.writeUTF(strMsg);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
// 关闭窗口事件监听
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
disconnected();
System.exit(0);
}
});
this.connect();
setVisible(true);
}
// 链接服务器地址
private void connect() {
try {
socket = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
thread = new Thread(new ChatThread());
thread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
// 断开连接
private void disconnected() {
bConnected = false;
try {
dos.close();
dis.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
// 开启线程接受服务器信息
private class ChatThread implements Runnable {
@Override
public void run() {
try {
bConnected = true;
while (bConnected) {
String msg = dis.readUTF();
String taText = ta.getText();
ta.setText(taText + msg + "
");
}
} catch (SocketException e) {
System.out.println("退出");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服务端:
package com.zhang.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class ChatServer {
private boolean started = false;
private List<ChatThread> chatThreads = new ArrayList<ChatThread>();
public static void main(String[] args) {
new ChatServer().startServer();
}
private void startServer() {
ServerSocket serverSocket=null;
try {
// 开启服务端Socket
serverSocket = new ServerSocket(8888);
started = true;
while (started) {
// 接受客户端连接请求
Socket socket = serverSocket.accept();
String RemoteIP =socket.getInetAddress().getHostAddress();
String RemotePort = ":"+socket.getLocalPort();
System.out.println("客户端"+RemoteIP+RemotePort+"已连接");
// 开启线程处理客户端通信
ChatThread ct = new ChatThread(socket);
chatThreads.add(ct);
new Thread(ct).start();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ChatThread implements Runnable {
private Socket socket;
private DataInputStream din = null;
private DataOutputStream don = null;
private boolean bConnected = false;
public ChatThread(Socket socket) {
this.socket = socket;
}
// 发送信息的函数
private void send(String strMsgIn) {
try {
don.writeUTF(strMsgIn);
don.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
try {
din = new DataInputStream(socket.getInputStream());
don = new DataOutputStream(socket.getOutputStream());
// 读取数据
bConnected = true;
while (bConnected) {
String strMsgIn = din.readUTF();
System.out.println(strMsgIn);
// 接收到数据后发送给每个客户端
for (int i = 0; i < chatThreads.size(); i++) {
chatThreads.get(i).send(strMsgIn);
}
}
} catch (IOException e) {
try {
// 如果客户端出错或关闭,直接关闭连接,并移除List中的当前线程
socket.close();
chatThreads.remove(this);
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
try {
din.close();
don.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
7、
package com.zhang.thread;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class IOTest {
public static void main(String[] args) throws Exception {
ReadFile();
WriteFile();
CopyPicture("pic.jpg", "哈哈哈.jpg");
CopyFile("a.txt", "f.txt");
}
/**
* 写文件
*/
private static void WriteFile() {
String s= "哈哈哈";
try {
//字节流写入文件
FileOutputStream fos = new FileOutputStream("1.txt");
fos.write(s.getBytes("UTF-8"));
fos.close();
// 字符流写入文件
FileWriter fw = new FileWriter("1.txt");
fw.write(s);
fw.close();
// 字符流写入文件
PrintWriter pw = new PrintWriter("1.txt", "utf-8");
pw.write(s);
pw.close();
//通过缓存写数据
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("2.txt")), "UTF-8"));
for (int i = 1; i < 100; i++) {
bw.write("哈哈哈" + i);
bw.newLine();
}
bw.close();
} catch (Exception e) {
System.err.println("write errors :" + e);
}
}
/**
* 读文件
*/
private static void ReadFile() {
StringBuilder result = new StringBuilder();
try {
//通过字符流读文件
FileReader fr = new FileReader("2.txt");
char[] buf = new char[1024];
int len =0;
while((len=fr.read(buf))!=-1){
String myStr = new String(buf, 0, len);
System.out.println(myStr);
}
fr.close();
// 字节流读文件
FileInputStream frs = new FileInputStream("1.txt");
byte[] bufs = new byte[1024];
int lens = 0;
while((lens=frs.read(bufs))!=-1){
String myStrs=new String(bufs, 0, lens,"UTF-8");
System.out.println(myStrs);
}
frs.close();
//通过缓存读书节
// BufferedReader bf = new BufferedReader(new FileReader("names.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("1.txt")), "UTF-8"));
String lineTxt = null;
while ((lineTxt = br.readLine()) != null) {
System.out.println(lineTxt);
result.append(lineTxt+"
");
}
br.close();
System.out.println(result.toString());
} catch (Exception e) {
System.err.println("read errors :" + e);
}
}
/**
* 通过字节流复制文件,可以复制文本文件和二进制文件,如图片
* @param oldfile
* @param newfile
* @throws Exception
*/
private static void CopyPicture(String oldfile, String newfile) throws Exception {
int len = 0;
byte[] buf = new byte[1024];
BufferedInputStream bufferedInputStream =new BufferedInputStream(new FileInputStream(new File(oldfile)));
BufferedOutputStream bufferedOutputStream =new BufferedOutputStream(new FileOutputStream(new File(newfile)));
while ((len = bufferedInputStream.read(buf)) != -1) {
bufferedOutputStream.write(buf, 0, len);
}
bufferedInputStream.close();
bufferedOutputStream.close();
}
/**
* 通过字符流复制文件,只能复制文本文件,如果复制二进制文件会出错
* @param oldfile
* @param newfile
* @throws Exception
*/
private static void CopyFile(String oldfile, String newfile) throws Exception{
BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(new FileInputStream(new File(oldfile)), "UTF-8"));
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(newfile)),"UTF-8"));
String len=null;
while((len=bufferedReader.readLine())!=null){
bufferedWriter.write(len);
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
}
}
8、
public static void main(String[] args) throws Exception {
FileManager a = new FileManager("a.txt", new char[] { '
' });
FileManager b = new FileManager("b.txt", new char[] { '
', ' ' });
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("c.txt")), "UTF-8"));
String aWord = null;
String bWord = null;
while ((aWord = a.nextWord()) != null) {
bufferedWriter.write(aWord);
bufferedWriter.newLine();
if ((bWord = b.nextWord()) != null) {
bufferedWriter.write(bWord);
bufferedWriter.newLine();
}
}
while ((bWord = b.nextWord()) != null) {
bufferedWriter.write(bWord);
bufferedWriter.newLine();
}
bufferedWriter.close();
}
}
class FileManager {
String[] words = null;
int pos = 0;
FileManager(String filename, char[] seperators) throws Exception {
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename)), "UTF-8"));
char[] buf = new char[1024];
int len = 0;
while ((len = bufferedReader.read(buf)) != -1) {
builder.append(new String(buf, 0, len));
}
bufferedReader.close();
String regex = null;
if (seperators.length > 1) {
regex = "" + seperators[0] + "|" + seperators[1];
} else {
regex = "" + seperators[0];
}
words = builder.toString().split(regex);
}
public String nextWord() {
if (pos == words.length){
return null;
}
return words[pos++];
}
9、查找Java文件夹下的全部.java文件,并复制到jad文件夹下后缀改为.jad
File srcDir = new File("java");
if (!(srcDir.exists() && srcDir.isDirectory())){
System.out.println("目录不存在");
}
File[] files = srcDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".java");
}
});
System.out.println(files.length);
File destDir = new File("jad");
if (!destDir.exists())
destDir.mkdir();
for (File f : files) {
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(f) );
String destFileName = f.getName().replaceAll("\.java$", ".jad");// \.java$ 正则表达式 结尾为.java的文件
BufferedOutputStream bufferedOutputStream =new BufferedOutputStream(new FileOutputStream(new File(destDir,destFileName)));
copy(bufferedInputStream, bufferedOutputStream);
bufferedInputStream.close();
bufferedOutputStream.close();
}
}
private static void copy(BufferedInputStream ips, BufferedOutputStream ops) throws Exception {
int len = 0;
byte[] buf = new byte[1024];
while ((len = ips.read(buf)) != -1) {
ops.write(buf, 0, len);
}
}
10、编写一个截取字符串的函数,输入为一个字符串和字节数,输出为按字节截取的字符串,但要保证汉字不被截取半个如“我ABC”,4,应该截取“我AB”,输入“我ABC汉DEF”,6,应该输出“我ABC”,而不是“我ABC+汉的半个”
public static void main(String[] args) throws Exception { String str = "我a爱中华abc我爱哈奥def"; //中文一个字占2个字节,UTF-8占3个字节。中文的字节码为负数。 int num = trimGBK(str.getBytes("GBK"), 7); System.out.println(str.substring(0, num)); } public static int trimGBK(byte[] buf, int n) { int num = 0; boolean bChineseFirstHalf = false; for (int i = 0; i < n; i++) { if (buf[i] < 0 && !bChineseFirstHalf) { bChineseFirstHalf = true; } else { num++; bChineseFirstHalf = false; } } return num; }
11、分别统计英文字符的数量,中文字符的数量,和数字字符的数量,假设字符中没有中文字符、英文字符、数字字符之外的其他特殊字符
public static void main(String[] args) throws Exception {
String str = "应该23vr输出我ABC而不是我ABC6tad73592汉的半个";
int engishCount = 0;
int chineseCount = 0;
int digitCount = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch >= '0' && ch <= '9') {
digitCount++;
} else if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
engishCount++;
} else {
chineseCount++;
}
}
System.out.println(engishCount + "***" + chineseCount + "****" + digitCount);
}
12、字符串匹配算法
String str1 ="abcdefg"; String str2= "cde"; char[] c1 = str1.toCharArray(); char[] c2=str2.toCharArray(); int i1=c1.length; int i2=c2.length; for (int i = 0; i < i1-i2; i++) { int j=0; while(j<i2&&c2[j]==c1[i+j]){ j++; if(j==i2){ return 1; } } } return 0;
13、打印*
private static void printstart(){ for(int i=1;i<=5;i++){//i--控制行 for(int j=5-i;j>=0;j--){//j--控制空格的数量 System.out.print(" "); } for(int k=1;k<=2*i-1;k++){//k--控制*的数量 System.out.print("*"); } System.out.println();//每循环一次换行 } }
14、计算1+11+111+1111+11111的和
private static void Sum(){ int a=0,sum=0; for(int n=1;n<=5;n++) { a=(a*10)+1; System.out.println(a); sum+=a; } System.out.print("sum="+sum); }
15、水仙花数
private static void shuixuanhua(){ for(int i=100;i<1000;i++){ int ge = i%10; int shi = i/10%10; int bai = i/10/10%10; if(i == (ge*ge*ge+shi*shi*shi+bai*bai*bai)){ System.out.println(i); } } }
16、map遍历
private static void listmap(){ Map<Integer, Integer> map=new HashMap<>(); map.put(0, 1); map.put(2, 3); map.put(4, 5); map.put(6, 7); map.put(8, 9); for (Integer key :map.keySet()) { System.out.println(key); } for (Integer key :map.values()) { System.out.println(key); } }
17、连接MySQL数据库
private static void jdbc() { Connection conn = null; PreparedStatement preparedStatement = null; try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123"); String sql = "select * from user"; preparedStatement = conn.prepareStatement(sql); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { String id = resultSet.getString(1); String name = resultSet.getString(2); Date time = resultSet.getDate(3); System.out.println(id + name + time); } } catch (Exception e) { e.printStackTrace(); } }
18 代码查错
abstract class Name {
private String name;
public abstract boolean isStupidName(String name) {}
}
//错。abstract method必须以分号结尾,且不带花括号
//public abstract boolean isStupidName(String name);
//**********************************************************
public class Something {
void doSomething () {
private String s = "";
int l = s.length();
}
}
//错。局部变量前不能放置任何访问修饰符 (private,public,和protected)。final可以用来修饰局部变量
//**********************************************************
abstract class Something {
private abstract String doSomething ();
}
//abstract的methods不能以private修饰。abstract的methods就是让子类implement(实现)具体细节。abstract method前也不能加final
//*********************************************************
public class Something {
public int addOne(final int x) {
return ++x;
}
}
//错。int x被修饰成final,意味着x不能在addOne method中被修改。
//**********************************************************
public class Something {
public static void main(String[] args) {
Other o = new Other();
new Something().addOne(o);
}
public void addOne(final Other o) {
o.i++;
}
}
class Other {
public int i;
}
//正确。在addOne method中,参数o被修饰成final。如果在addOne method里我们修改了o的reference(比如: o = new Other();),那么如同上例这题也是错的。但这里修改的是o的member vairable(成员变量),而o的reference并没有改变
//引用不能改变但是引用中对象的内容可以改变
//**********************************************************
class Something {
int i;//正确,默认为0
final int i;//错误,final int i =0; final修饰的没有默认值
public void doSomething() {
System.out.println("i = "+ i);
}
}
//*********************************************************
public class Something {
public static void main(String[] args) {
Something s = new Something();
System.out.println("s.doSomething() returns " + doSomething());
}
public String doSomething() {
return "Do something ...";
}
}
//静态方法里不能调用非静态方法
//**********************************************************
interface A {
int x = 0;
}
class B {
int x = 1;
}
class C extends B implements A {
public void pX() {
System.out.println(x);//编译时报错
//System.out.println(A.x);
//System.out.println(super.x);
}
public static void main(String[] args) {
new C().pX();
}
}
//**********************************************************
interface Playable {
void play();
}
interface Bounceable {
void play();
}
interface Rollable extends Playable, Bounceable {
Ball ball = new Ball("PingPang");//默认为public static final Ball ball = new Ball("PingPang");
}
class Ball implements Rollable {
private String name;
public String getName() {
return name;
}
public Ball(String name) {
this.name = name;
}
public void play() {
ball = new Ball("Football");//final修饰的对象,引用是不能被改变的。所以报错
System.out.println(ball.getName());
}
}