能不能同步,就是要看使用的是不是同一把?
wait 和notify
class Res {
public String userName;
public String sex;
public boolean flag = false;
}
class InputThread extends Thread {
private Res res;
public InputThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0;
while (true) {
synchronized (res) {
if (res.flag) {
try {
res.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
if (count == 0) {
res.userName = "余胜军";
res.sex = "男";
} else {
res.userName = "小红";
res.sex = "女";
}
count = (count + 1) % 2;
res.flag = true;
res.notify();
}
}
}
}
class OutThrad extends Thread {
private Res res;
public OutThrad(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
if (!res.flag) {
try {
res.wait();
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println(res.userName + "," + res.sex);
res.flag = false;
res.notify();
}
}
}
}
public class ThreadDemo01 {
public static void main(String[] args) {
Res res = new Res();
InputThread inputThread = new InputThread(res);
OutThrad outThrad = new OutThrad(res);
inputThread.start();
outThrad.start();
}
}
wait和sleep的区别
Lock锁
class OutThrad extends Thread {
private Res res;
private Condition newCondition;
public OutThrad(Res res,Condition newCondition) {
this.res = res;
this.newCondition=newCondition;
}
@Override
public void run() {
while (true) {
try {
res.lock.lock();
if (!res.flag) {
try {
newCondition.await();//不是wait
} catch (Exception e) {
// TODO: handle exception
}
}
System.out.println(res.userName + "," + res.sex);
res.flag = false;
newCondition.signal();//唤醒
} catch (Exception e) {
// TODO: handle exception
}finally {
res.lock.unlock();
}
}
}
}
public class ThreadDemo01 {
public static void main(String[] args) {
Res res = new Res();
Condition newCondition = res.lock.newCondition();
InputThread inputThread = new InputThread(res,newCondition);
OutThrad outThrad = new OutThrad(res,newCondition);
inputThread.start();
outThrad.start();
}
}
如何停止线程
class StopThread extends Thread {
private volatile boolean flag = true;
@Override
public synchronized void run() {
System.out.println("子线程开始....");
while (flag) {
try {
wait();
} catch (InterruptedException e) {
// e.printStackTrace();
stopThread();
}
}
System.out.println("子线程结束....");
}
public void stopThread() {
flag = false;
}
}
public class StopThreadDemo {
public static void main(String[] args) {
StopThread stopThread = new StopThread();
stopThread.start();
for (int i = 1; i < 10; i++) {
try {
Thread.sleep(1000);
System.out.println("i:" + i);
if (i == 8) {
// stopThread.stopThread();
stopThread.interrupt();
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}