一、客户端读/写
Socket s = new Socket("127.0.0.1",5000); InputStreamReader stream = new InputStreamReader(s.getInputStream()); BufferedReader reader = new BufferedReader(stream); String message = reader.readLine();
PrintWriter writer = new PrintWrite(s.getOutputStream());//写到客户端上 writer.println("Send:");
二、服务器
ServerSocket s = new ServerSocket(5000); Socket sock = s.accept();
三、线程
public class MyRunnable implements Runnalbe{ @override public void run(){...} } class ThreadTest{ public static void main(String [] args){ Runnable threadJob = new MyRunnable(); Thread myThread = new Thread(threadJob); myThread.start(); } }
Thread.sleep(2000);//一定程度上可以让线程按照预想的顺序执行
在线程中执行的方法,需要避免死锁,在关键的地方上加上synchronized来让方法或者程序块变成原子性
基础篇——网络与线程
时间: 2024-10-21 10:38:20