먼저, 여러 스레드 사이의 통신 무엇인가
1. 컨셉 : 다중 스레드, 사실 여러 스레드, 같은 자원을 운영하지만 서로 다른 이동 작업 사이의 통신.
둘째, 다중 스레드 통신은 시뮬레이션 문제를 신흥
1. 수요 제 1 스레드 기록 (입력)은 사용자가 다른 스레드 인출하여 읽기, 쓰기 동작을 달성하기 위해 사용자 (를) 판독.
2. 코드
// 共享对象
class Res {
// 姓名
public String name;
// 性别
public String sex;
}
// 生产这线程
class IntThread extends Thread {
public Res res;
public IntThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0; // 1
while (true) {
if (count == 0) {
res.name = "小红";
res.sex = "女";
} else {
res.name = "小明";
res.sex = "男";
}
count = (count + 1) % 2;// 0 1 0 1 0 1
}
}
}
// 读取线程
class OutThread extends Thread {
public Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
System.out.println(res.name + "," + res.sex);
}
}
}
public class Test0001 {
public static void main(String[] args) throws InterruptedException {
Res res = new Res();
IntThread intThread = new IntThread(res);
OutThread outThread = new OutThread(res);
intThread.start();
outThread.start();
}
}
3. 결과
참고 : 데이터가 혼동되지 스레드 안전 문제를 야기
셋째, 멀티 스레드 통신 시뮬레이션은 문제를 해결하기 위해
1. 코드
// 共享对象
class Res {
// 姓名
public String name;
// 性别
public String sex;
// 为true情况下 允许读,不能写
// 为false情况下 允许写,不能读。
public boolean flag = false;
}
// 生产这线程
class IntThread extends Thread {
public Res res;
public IntThread(Res res) {
this.res = res;
}
@Override
public void run() {
int count = 0; // 1
while (true) {
synchronized (res) {
if (res.flag) {
try {
res.wait();// 釋放当前锁对象
} catch (Exception e) {
// TODO: handle exception
}
}
if (count == 0) {
res.name = "小红";
res.sex = "女";
} else {
res.name = "小明";
res.sex = "男";
}
count = (count + 1) % 2;// 0 1 0 1 0 1
res.flag = true;// 标记当前线程为等待
res.notify();// 唤醒被等待的线程
}
}
}
}
// 读取线程
class OutThread extends Thread {
public Res res;
public OutThread(Res res) {
this.res = res;
}
@Override
public void run() {
while (true) {
synchronized (res) {
try {
if (!res.flag) {
res.wait();
}
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(res.name + "," + res.sex);
res.flag = false;
res.notify();
}
}
}
}
public class Test0001 {
public synchronized static void main(String[] args) throws InterruptedException {
Res res = new Res();
IntThread intThread = new IntThread(res);
OutThread outThread = new OutThread(res);
intThread.start();
outThread.start();
}
}
2. 결과
분석 (3)
이 개체의 잠금을 포함하기 때문에 3.1., 그들은 동기 사용에 배치해야합니다. 잠깐, 동기화 내부를 사용할 수 있는지 알려주십시오.
3.2.Wait 필수의 임시 스레드는 현재 다른 스레드를 실행할 수있는 기회를 가질 수 그래서, 실행 및 자원 잠금을 해제합니다.
참고 : 사용 스레드 동기화해야하고, 같은 잠금 리소스
넷째, 작은 복지
그리고 차이 1.wait 잠
슬립 () 메소드를 들어, 우리는 먼저 Thread 클래스 속한 알 필요가있다. 그리고 대기 () 메소드는, 객체는 클래스에 속한다.
프로그램에서 수면 () 메소드의 결과는, 지정된 시간을 중단하기 위해 다른 스레드의 CPU, 그러나 그의 유해는 지정된 시간에 자동으로 작동을 재개합니다 최대 인 상태를 모니터링하고 그래서.
수면 () 메서드를 호출하는 동안 스레드가 개체의 잠금을 해제하지 않습니다.
그리고 통화 대기 () 메소드는 스레드 만 작업에 개체 잠금을 획득 할 객체 잠금 풀 준비가 이동하기 전에 스레드의이 객체 () 메소드에 대한 통지 호출 한 후 잠금 풀에 대한 대기이 객체의 대기로 오브젝트 잠금을 포기 때 .
다섯째, 말
항상 믿음을 유지!