package com.donzell.donzell;
/**
*
* @author DONZELL
* 本用力演示线程同步等待事例
* 线程1执行5次==>线程1等待线程2执行5次==>线程2等待线程1执行5次==>线程1完成线程2执行
*
*/
public class ThreadTest {
public int value = 0;
public void add1(){
synchronized (this) {
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.value ++;
System.out.println("线程1执行后value的值为===>"+value);
if(value == 5){
try {
//线程1执行5次后进入等待状态释放锁,次数线程2无需调用notify,便会自己拿到锁进入执行
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//线程1执行完,通知线程2
notify();
}
}
public void add2(){
synchronized (this) {
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.value ++;
System.out.println("线程2执行后value的值为===>"+value);
if(value == 10){
try {
notify();
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
final ThreadTest threadTest = new ThreadTest();
final Thread t1 = new Thread(new Runnable() {
public void run() {
threadTest.add1();
}
});
final Thread t2 = new Thread(new Runnable() {
public void run() {
threadTest.add2();
}
});
t1.start();
//休眠200ms保证线程1先于线程2执行
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}
/**
*
* @author DONZELL
* 本用力演示线程同步等待事例
* 线程1执行5次==>线程1等待线程2执行5次==>线程2等待线程1执行5次==>线程1完成线程2执行
*
*/
public class ThreadTest {
public int value = 0;
public void add1(){
synchronized (this) {
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.value ++;
System.out.println("线程1执行后value的值为===>"+value);
if(value == 5){
try {
//线程1执行5次后进入等待状态释放锁,次数线程2无需调用notify,便会自己拿到锁进入执行
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//线程1执行完,通知线程2
notify();
}
}
public void add2(){
synchronized (this) {
for(int i=0;i<10;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.value ++;
System.out.println("线程2执行后value的值为===>"+value);
if(value == 10){
try {
notify();
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
final ThreadTest threadTest = new ThreadTest();
final Thread t1 = new Thread(new Runnable() {
public void run() {
threadTest.add1();
}
});
final Thread t2 = new Thread(new Runnable() {
public void run() {
threadTest.add2();
}
});
t1.start();
//休眠200ms保证线程1先于线程2执行
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
}