------- android培训、java培训、期待与您交流! ----------
线程间的通信:两个线程对同一个数据做不同操作的安全问题
看以下代码:
class src {
String name;
String sex;
}
class Input implements Runnable {
private src s;
boolean flag;
public Input(src s) {
this.s = s;
}
public void run() {
flag = true;
while (true) {
if (flag) {
s.name = "张三";
s.sex = "男";
flag = false;
} else {
s.name = "李思";
s.sex = "女";
flag = true;
}
}
}
}
class Output implements Runnable {
private src s;
public Output(src s) {
this.s = s;
}
public void run() {
while (true) {
System.out.println("姓名:" + s.name + "……性别:" + s.sex);
}
}
}
class InputOutputDemo {
public static void main(String[] args) {
src s = new src();
Input in = new Input(s);
Output out = new Output(s);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
运行结果如图所示:
出现了明显的错误,这是因为数据不同步造成的,加了synchronized则很好的解决了这个问题。
代码如下:
class src {
String name;
String sex;
}
class Input implements Runnable {
private src s;
boolean flag;
public Input(src s) {
this.s = s;
}
public void run() {
flag = true;
while (true) {
synchronized (s) {
if (flag) {
s.name = "张三";
s.sex = "男";
flag = false;
} else {
s.name = "李思";
s.sex = "女";
flag = true;
}
}
}
}
}
class Output implements Runnable {
private src s;
public Output(src s) {
this.s = s;
}
public void run() {
while (true) {
synchronized (s) {
System.out.println("姓名:" + s.name + "……性别:" + s.sex);
}
}
}
}
class InputOutputDemo {
public static void main(String[] args) {
src s = new src();
Input in = new Input(s);
Output out = new Output(s);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
如果是要间隔打印,则要使用的wait()和notify()方法。比如Inputout往数据源处存储一数据,存储后则要进入wait()状态,并把Output线程唤醒,等Output取出数据后在使用wait()方法等待,并把intput线程用notify唤醒。
代码如下:
class src {
public boolean empty = true;
String name;
String sex;
}
class Input implements Runnable {
private src s;
boolean flag;
public Input(src s) {
this.s = s;
}
public void run() {
flag = true;
while (true) {
synchronized (s) {
if (!s.empty)
try {
s.wait();
} catch (Exception e) {
}
if (flag) {
s.name = "张三";
s.sex = "男";
flag = false;
} else {
s.name = "李思";
s.sex = "女";
flag = true;
}
s.empty = false;
s.notify();
}
}
}
}
class Output implements Runnable {
private src s;
public Output(src s) {
this.s = s;
}
public void run() {
while (true) {
synchronized (s) {
if (s.empty)
try {
s.wait();
} catch (Exception e) {
}
System.out.println("姓名:" + s.name + "……性别:" + s.sex);
s.empty = true;
s.notify();
}
}
}
}
class InputOutputDemo {
public static void main(String[] args) {
src s = new src();
Input in = new Input(s);
Output out = new Output(s);
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
t1.start();
t2.start();
}
}
运行结果 :