解决多线程安全问题的方式:
* synchronzed
* 1,同步代码块
* 2,同步方法
* 3,同步锁Lock
* 用lock()上锁,用unlock()释放锁
1,volatitle
2,虚假唤醒
3,condition线程间通信
4,CountDownLatch
闭锁,只有其他所有线程的运算全部完成,但前运算才继续执行
5,CopyOnWriteArrayList
写入并复制
* 添加操作低时,效率低,支持并发操作,并发迭代操作多时可以选择
6,生产者消费者实例
/*package ProductAndCustomer;
* 为了避免虚假唤醒,应该使用while循环
public class ProCus {
public static void main(String[] args) {
Clerk clerk=new Clerk();
Productor productor=new Productor(clerk);
Customer customer=new Customer(clerk);
new Thread(productor,"生产者A").start();
new Thread(customer,"消费者B").start();
new Thread(productor,"生产者C").start();
new Thread(customer,"消费者D").start();
}
}
class Clerk{
private int pro=0;
public synchronized void get() {
while(pro>=10) {
System.out.println("产品已满");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ ++pro);
this.notifyAll();
}
public synchronized void sale() {
while(pro<=0) {
System.out.println("缺货");
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+":"+ --pro);
this.notifyAll();
}
}
class Productor implements Runnable{
private Clerk clerk;
public Productor(Clerk clerk) {
this.clerk=clerk;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
clerk.get();
}
}
}
class Customer implements Runnable{
private Clerk clerk;
public Customer(Clerk clerk) {
this.clerk=clerk;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
clerk.sale();
}
}
}
*/
7,ReadWriteLock
读写锁
* 写写和读写 需要互斥
* 读读不需要互斥
public class ReadWrite {
public static void main(String[] args) {
ReadWriteDemo rDemo=new ReadWriteDemo();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
rDemo.write((int)(Math.random()*101));
}
},"write").start();
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
rDemo.read();
}
},"read").start();
}
}
}
class ReadWriteDemo{
private ReadWriteLock lock=new ReentrantReadWriteLock();
private int Number=0;
public void read() {
lock.readLock().lock();
try {
System.out.println(Thread.currentThread().getName()+":"+Number);
} finally {
// TODO: handle finally clause
lock.readLock().unlock();
}
}
public void write(int Number) {
lock.writeLock().lock();
try {
System.out.println(Thread.currentThread().getName());
this.Number=Number;
} finally {
// TODO: handle finally clause
lock.writeLock().unlock();
}
}
}