多线程下的单例模式
懒汉模式
public class ThreadDanli {
//这里的volatile 主要是为了防止指令重排
private static volatile ThreadDanli threadDanli = null;
private ThreadDanli() {
}
public static ThreadDanli getThreadDanli() {
//双重检测锁
if (threadDanli == null) {
synchronized (ThreadDanli.class) {
if (threadDanli == null) {
threadDanli = new ThreadDanli();
}
}
}
return threadDanli;
}
public static void main(String[] args) {
Thread tdOne = new TDOne();
Thread tdTwo = new TDTwo();
tdOne.start();
tdTwo.start();
}
}
class TDOne extends Thread {
@Override
public void run() {
System.out.println(ThreadDanli.getThreadDanli());
}
}
class TDTwo extends Thread {
@Override
public void run() {
System.out.println(ThreadDanli.getThreadDanli());
}
}
生产者和消费者
生产字符进数组,消费数组中的字符,同时进行
public class ProAndCon {
public static void main(String[] args) {
Center center = new Center();
Thread pro = new Pro(center);
Thread con = new Con(center);
pro.start();
con.start();
}
}
class Pro extends Thread {
Center center;
public Pro(Center center) {
this.center = center;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
center.pro((char) (i+'a'));
}
}
}
class Con extends Thread {
Center center;
public Con(Center center) {
this.center = center;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
center.con((char) (i+'a'));
}
}
}
class Center {
char[] charArr = new char[6];
int count;
public synchronized void pro(char c){
if (count >= charArr.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count < charArr.length && count >= 0){
this.notifyAll();
}
charArr[count] = c;
count++;
System.out.println("you procedure " + c +" and you have" + count);
}
public synchronized void con(char c){
if (count == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (count >0 && count <= charArr.length) {
this.notifyAll();
}
count--;
char result = charArr[count];
System.out.println("you consume "+result+" and you have last" + count);
}
}
网络编程
快速定位一台计算机
IP:IPV4,IPV6
端口:0-65535
- mysql:3306
- tomcat:8080
- HTTP:80
- Redis:6379
- PhpStudy:8088
IP+端口 = socket
127.0.01(localhost) 本地地址
TCP协议:
Ø使用TCP协议前,须先建立TCP连接,形成传输数据通道
Ø 传输前,采用“三次握手”方式,点对点通信,是可靠的
Ø TCP协议进行通信的两个应用进程:客户端、服务端。
Ø 在连接中可进行大数据量的传输
Ø 传输完毕,需释放已建立的连接,效率低
UDP协议:
Ø 将数据、源、目的封装成数据包,不需要建立连接
Ø 每个数据报的大小限制在64K内
Ø 发送不管对方是否准备好,接收方收到也不确认,故是不可靠的
Ø 可以广播发送
Ø 发送数据结束时无需释放资源,开销小,速度快