Executor执行器类,ExecutorService具有生命周期的执行器;
Thread.yield()让步,让出CPU,
t.join,加入一个线程t,让t先执行;
suspend()和resume();废弃的方法;
解决资源抢占修改对象:synchronize 或者;锁是对于同一个类的;notify(),wait()
ReentrantLock 类的lock(),unlock函数;Condition类的await(),signal(),signalAll();
public Lock lock = new ReentrantLock();
//创建三个Condition对象 分别用于控制三个线程
public Condition condition1 = lock.newCondition();
一个int变量,判断,不是该方法就等待,是的话执行,之后signalAll()
volidate关键字:表示直接与内存同步,读取在主存中;编译器不执行编译和读写的优化;
原子类AtomicInteger,AtomicLong类;因为基本类型读写会因并发问题导致出错;
ThreadLocal表示线程本地存储,线程复制的一份变量;
线程之间的协作,1:notify(),wait();lock(),unlock函数;Condition类的await(),signal(),signalAll();
2:生产者和消费者:可以使用线程之间的通信,上面的;可以使用队列BlockingQueue,ArrayBlockingQueue有界的,LinkedBlockingQueue无界的;一般面对对象的思想,线程类的构造方法传入该队列
public static void main(String[] args)
{
/* PipedWriter out=new PipedWriter();
PipedReader reader=new PipedReader();*/
LinkedList<Integer> list = new LinkedList<>();
Producer p = new Producer(list, 10);
Consumer c1 = new Consumer(list);
Consumer c2 = new Consumer(list);
Thread producer = new Thread(p);
producer.setName("生产者线程");
Thread consumer1 = new Thread(c1);
consumer1.setName("消费者1");
Thread consumer2 = new Thread(c2);
consumer2.setName("消费者2");
producer.start();
consumer1.start();
consumer2.start();
}
3:任务间使用管道输入输出,管道就是封装好的解决方案,PipedWriter(),PipedReader();读管道绑定写管道就可以了;
死锁:任务链上相互等待,且不释放资源,
https://www.cnblogs.com/yangenyu/p/11545072.html
String B="B" 和new String("B")不是一个对象引用
死锁通常是锁住对象A,内锁对象B,解锁我还不会。
public class DeadLock1 {
public static void main(String[] args) {
Lock lock1 = new ReentrantLock();
Lock lock2 = new ReentrantLock();
new Thread(new Resource1(lock1,lock2),"A").start();
new Thread(new Resource1(lock2,lock1),"B").start();
}
}
class Resource1 implements Runnable{
Lock lock1;
Lock lock2;
public Resource1(Lock lock1,Lock lock2){
this.lock1 = lock1;
this.lock2 = lock2;
}
@Override
public void run() {
lock1.lock();
try{
System.out.println(Thread.currentThread().getName());
Thread.sleep(2);
if(lock2.tryLock(100, TimeUnit.SECONDS)){
lock2.lock();
try{
System.out.println(Thread.currentThread().getName());
}finally {
lock2.unlock();
}
}
else{
lock1.unlock();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock1.unlock();
}
}
}