jixu
8. 并发
启动线程的几种方式
Thread t7 = new Thread(timer);
t7.start();
Thread.sleep(100) //暂停当前线程
class MT extends Thread {
private int n;
public MyThread( int n ){
super();
this.n=n;
}
public void run() {
for(int i=0;i<n;i++) {
System.out.println(i);
}
}
} Class MT implements Runnable{
private int n;
public MyTask(int n){
this.n = n;
}
public void run() {
for(int i=0; i<n; i++) {
System.out.println(i);
}
}
} new Thread(){
public void run() {
for(int i=0; i<10; i++)
System.out.println(i);
}
}.start(); new Thread( ( ) -> {
for(int i=0; i<10; i++)
System.out.println(i);
} ).start();
线程同步
- synchronize:对象加锁
synchronized(cnt) {
cnt++; //临界区
}- wait() 释放对象锁,阻塞当前进程
- notify() / notifyAll() 相当于signal,让阻塞的线程继续
java并发API:java.util.concurrent
原子变量:保证线程安全
AtomicInteger cnt=new AtomicInteger(0);
cnt.getAndIncrement();
集合:
ArrayList/HashMap不是线程安全的
Vector及Hashtable是线程安全的
CopyOnWriteArrayList、 CopyOnWriteArraySet:适合于很少写入而读取频繁的对象
ConcurrentHashMap:putIfAbsent(), remove(), replace()
队列:
BlockingQueue<Integer> q=new ArrayBlockingQueue<>(3); put() take()
线程池
class ThreadPoolDemo
{
public static void main(String[] args) {
ExecutorService pool=Executors.newCachedThreadPool();
MyTask t1=new MyTask(5); MyTask t2=new MyTask(7);
pool.execute(t1); pool.execute(t2);
pool.shutdown();
}
}
class MyTask implements Runnable {
int n=10;
public MyTask(int n){ this.n=n;}
public void run(){
for(int i=0;i<n; i++)System.out.print(i);
}
}
实现一个生产者-消费者问题
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i <10; i++)
cubbyhole.put(i);
}
} class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i <10; i++)
value = cubbyhole.get();
}
} class CubbyHole {
private int data[] = new int[3];
private int index = 0;
public synchronized int get() {
while (index <= 0) {
try{
wait(); //waits for notify() from Producer
} catch (InterruptedException e) { }
}
index --;
int value = data[index];
System.out.println("Consumer got: " + data[index]);
notify();
return value;
}
public synchronized void put(int value) {
while (index >= data.length) {
try{
wait(); //waits for notify() from consumer
} catch (InterruptedException e) { }
}
System.out.println("Producer put: " + value);
data[index] = value;
index ++;
notify();
}
} class ProducerConsumerStack {
public static void main(String args[]) {
CubbyHole c = new CubbyHole();
Producer p1=new Producer(c,1);
Consumer c1=new Consumer(c,1);
p1.start();
c1.start();
}
}
Ref:https://github.com/CyC2018/CS-Notes/blob/master/notes/Java%20%E5%B9%B6%E5%8F%91.md