1 实现一个线程+1 一个线程 -1
class Share511 {
public int a = 0;
}
class Thread552 implements Runnable{
Share511 share;
@Override
public void run() {
while(true){
synchronized (share) {
int a = share.a;
if(a == 0){
share.a =a+1;
System.out.println("a+1 " + share.a);
share.notify();
}else{
try {
share.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public Thread552(Share511 share) {
this.share = share;
}
}
class Thread553 implements Runnable{
Share511 share;
@Override
public void run() {
while(true){
synchronized (share) {
int a = share.a;
if(a == 1){
share.a = a - 1;
System.out.println("a-1 " + share.a);
share.notify();
}else{
try {
share.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public Thread553(Share511 share) {
this.share = share;
}
}
public class Thread5 {
public static void main(String[] args) {
Share511 share511 = new Share511();
Thread thread552 = new Thread(new Thread552(share511));
thread552.start();
Thread thread553 = new Thread(new Thread553(share511));
thread553.start();
}
}
2 sleep()与wait()区别
- sleep()属于方法是属于Thread类中的方法
- sleep()不会释放对象锁wait()对象锁
3 Lock写法:
Lock lock = new ReentrantLock();
lock.lock();
try{
//可能会出现线程安全的操作
}finally{
//一定在finally中释放锁
//也不能把获取锁在try中进行,因为有可能在获取锁的时候抛出异常
lock.ublock();
}
4 Condition用法
Condition condition = lock.newCondition();
condition.await(); 类似wait
Condition.signal() 类似notify
5 守护线程
Java中有两种线程一种是用户线程,另一种是守护线程
当进程不存在或主线程停止守护线程也会被停止
使用setDaemon(true)方法设置为守护线程