java允许多线程并发控制,当多个线程同时操作一个可共享的资源变量时(如数据的增删改查), 将会导致数据不准确,相互之间产生冲突,因此加入同步锁以避免在该线程没有完成操作之前,被其他线程的调用,从而保证了该变量的唯一性和准确性。
我们来看java中第二种同步的方式,使用同步方法。
/**
* 线程间通讯,多个线程处理同一个资源,但是任务不一样
* @author xj
*
*/
/*
* 定义资源
*/
class Resource2{
String name;
String sex;
Boolean flag = false;
public synchronized void set(String name, String sex){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name;
this.sex = sex;
flag = true;
notify();
}
public synchronized void out(){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.name + " : " + this.sex);
flag = false;
notify();
}
}
/*
* input 输入操作
*/
class Input2 implements Runnable{
private Resource2 r;
public Input2(Resource2 r) {
this.r = r;
}
public void run(){
int x = 0;
while(true){
if(x == 0){
r.set("zhangsan", "男");
}
else {
r.set("Lisi", "女");
}
x = (x + 1)%2;
}
}
}
/**
* 输出
* @author xj
*
*/
class Output2 implements Runnable{
Resource2 r;
public Output2(Resource2 r) {
this.r = r;
}
public void run(){
while(true){
r.out();
}
}
}
public class ResourceDemon02 {
public static void main(String[] args) {
// 创建资源
Resource2 r = new Resource2();
// 创建任务
Input2 in = new Input2(r);
Output2 out = new Output2(r);
//创建线程,执行路径
Thread t1 = new Thread(in);
Thread t2 = new Thread(out);
//线程启动
t1.start();
t2.start();
}
}