同步容器:
//Vector ArrayList CopyOnWriteArrayList
ArrayList<String> s=new ArrayList<>();
Collections.synchronizedList(s);
//Hashtable HashMap ConcurrentHashMap
HashMap<String, Object> resHashMap=new HashMap<>();
Collections.synchronizedMap(resHashMap);
}
BlockingQueue:
put和Take 阻塞的
Add和Remove抛出异常
Offer和poll 有返回值得
public class Demo33 {
public static void main(String[] args) {
ThreadPoolExecutor threadPool=
new ThreadPoolExecutor(10,20,10,TimeUnit.DAYS,
new ArrayBlockingQueue<>(10),
new DiscardOldestPolicy());
AtomicInteger count=new AtomicInteger();
for(int i=0;i<100;i++){
threadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
count.getAndIncrement();
}
});
}
threadPool.shutdown();
while(Thread.activeCount()>1){
}
System.out.println(count.get());
}
}
public class Demo44 {
public static void main(String[] args) {
//10.个线程来处理大量的任务
//ThreadPoolExecutor pool=new ThreadPoolExecutor(10,10,0,TimeUnit.MILLISECONDS,
//new LinkedBlockingQueue<>());
ExecutorService pool=Executors.newFixedThreadPool(10);
ExecutorService pool1=Executors.newCachedThreadPool();
ExecutorService pool2=Executors.newSingleThreadExecutor();
ExecutorService pool3=Executors.newScheduledThreadPool(10);
ThreadFactory tf=new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread=newThread(r);
return null;
}
};
while(true){
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
}
实现简单的解析web:
public class HttpService2 {
public static void main(String[] args) throws Exception{
ExecutorService pool=Executors.newCachedThreadPool();
ServerSocket server=new ServerSocket(8888);
System.out.println("服务器启动,监听"+8888+"端口");
while(!Thread.interrupted()){
Socket client=server.accept();
pool.execute(new ServerThread(client));
//new Thread(new ServerThread(client)).start();
}
}
}
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class ServerThread implements Runnable{
private static Map<String, String> contentMap=new HashMap<>();
static{
contentMap.put("html", "text/html;charset=utf-8");
contentMap.put("jpg", "image/jpeg");
}
private Socket client;
private InputStream ins;
private OutputStream out;
private PrintWriter pw;
private BufferedReader br;
public ServerThread(Socket client) {
this.client=client;
init();
}
private void init() {
try {
ins=client.getInputStream();
out=client.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run(){
try {
go();
} catch (Exception e) {
e.printStackTrace();
}
}
private static final String webroot="";
public void go() throws Exception{
//读取请求信息
BufferedReader reader=new BufferedReader(new InputStreamReader(ins));
String line=reader.readLine().split(" ")[1].replace("/", "\\");
System.out.println(line);
if(line.equals("\\")){
line +="index.html";
}
//给用户响应
PrintWriter pw=new PrintWriter(out);
InputStream i=new FileInputStream(webroot+line);
//BufferedReader fr=new BufferedReader(new InputStreamReader(i));
pw.println("HTTP/1.1 200 OK");
pw.print("Content-Type:"+
contentMap.get(line.substring(
line.lastIndexOf(".")+1,line.length())));
pw.println("Content-Length:"+i.available());
pw.flush();
String c=null;
byte[] buff=new byte[1024];
int len=0;
while((len=i.read(buff))!=-1){
out.write(buff,0,len);
}
// while((c=fr.readLine())!=null){
// pw.print(c);
// }
pw.flush();
//i.close();
//fr.close();
pw.close();
reader.close();
client.close();
}
}
StampedLock:读锁并不会阻塞写锁
import java.util.concurrent.locks.StampedLock;
public class Demo55 {
private int balance;
private StampedLock lock=new StampedLock();
public void conditionReadWrite(int value){
//判断balance是否符合跟新的条件
long stamp=lock.readLock();
while (balance>0) {
//转换成写锁
long writeStamp=lock.tryConvertToWriteLock(stamp);
if(writeStamp!=0){ //成功转换成写锁
stamp=writeStamp;
balance+=value;
break;
}else { //没有转换成写锁,首先释放读锁,然后在拿到写锁
lock.unlock(stamp);
//获取写锁
stamp=lock.writeLock();
}
}
lock.unlock(stamp);
}
//获取乐观锁
public void optimisticRead(){
long stamp=lock.tryOptimisticRead();
int c=balance;
//可能出现写操作,需要判断
if(!lock.validate(stamp)){
//重新读取
long readStamp= lock.readLock();
c=balance;
stamp=readStamp;
}
lock.unlock(stamp);
}
public void read(){
long stamp= lock.readLock();
int c=balance;
lock.unlockRead(stamp);
}
public void write(int value){
long stmp= lock.writeLock();
balance +=value;
lock.unlock(stmp);
}
}
public class Demo77 {
private int a;
private boolean flag;
public void write(){
//这两个数据之间没有数据依赖性,因此处理器会对这两行代码进行指令重排序
a=1;
flag=true;
}
public void reader(){
if(flag){
int b=a+1;
System.out.println(b);
}
}
}
当写一个volatile变量时,java 内存模型会把该线程对应的本地内存中的共享变量值刷新到主内存中
当读一个volatile变量时,Java内存模型会把当前线程对应的本地内存 中的共享变量置为无效,然后从主内从中读取共享变量