public class ThreadTest {
public static void main(String[] args) {
Print p = new Print();
Num n = new Num(p);
A a = new A(p);
Thread t1 = new Thread(n);
Thread t2 = new Thread(a);
t1.start();
t2.start();
}
}
//打印
class Print{
boolean flag = false;
//synchronized 修饰方法/代码块 会调用锁保护方法/代码块
public synchronized void printnum() throws InterruptedException {
for(int i=1;i<=52;i++) {
while(flag) {
this.wait();
}
System.out.print(i);
if(i%2==0) {
flag = true;
this.notifyAll();
}
}
}
//synchronized 修饰方法/代码块 会调用锁保护方法/代码块 flag 被保护
public synchronized void printa() throws InterruptedException {
for(int i=1;i<=26;i++) {
while(!flag) {
this.wait();
}
System.out.print((char)(i+64));
flag = false;
this.notifyAll();
}
}
}
//数字
class Num implements Runnable{
Print p;
public Num(Print p) {
super();
this.p = p;
}
public void run() {
try {
p.printnum();
}catch (Exception e) {
e.printStackTrace();
}
}
}
//字母
class A implements Runnable{
Print p;
public A(Print p) {
super();
this.p = p;
}
public void run() {
try {
p.printa();
}catch (Exception e) {
e.printStackTrace();
}
}
}
当多个线程对同一个资源进行访问和操作的时候就会出现数据一致性问题。一致性问题得不到解决多个任务的操作永远得不到正确的结果,解决一致性问题的方法就是同步机制。