package com.thread;
//两个线程,子线程10次,主线程5次,子线程10次,主线程5次,如此往复50次
//首先实现互斥,然后实现通信
public class TranditionalThreadCommunication {
final Business business = new Business();
public static void main(String[] args) {
new TranditionalThreadCommunication().init();
}
private void init() {
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<50;i++)
{
business.main();
}
}
}).start();
for(int i=0;i<50;i++)
{
business.sub();
}
}
class Business {
private Boolean isShouldSub = true;
public synchronized void main() {
if (!isShouldSub) {
for (int i = 0; i < 5; i++) {
System.out.println("主线程第" + i + "次");
}
isShouldSub = true;
this.notify();
} else {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized void sub() {
if (isShouldSub) {
for (int j = 0; j < 10; j++) {
System.out.println("子线程第" + j + "次");
}
isShouldSub = false;
this.notify();
} else {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
利用condition和lock实现互斥和通信
package com.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
//利用condition和lock实现互斥和通信
//两个线程,子线程10次,主线程5次,子线程10次,主线程5次,如此往复50次
//首先实现互斥,然后实现通信
public class ConditionCommunication {
final Business business = new Business();
public static void main(String[] args) throws InterruptedException {
new ConditionCommunication().init();
}
private void init() throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
business.main();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
for (int i = 0; i < 50; i++) {
business.sub();
}
}
class Business {
private Boolean isShouldSub = true;
ReentrantLock lock = new ReentrantLock();
Condition condition=lock.newCondition();
public void main() throws InterruptedException {
try {
lock.lock();
if (isShouldSub) {
System.out.println("主线程等待");
condition.await();
} else {
System.out.println("主线程锁上了!");
for (int i = 0; i < 5; i++) {
System.out.println("主线程第" + i + "次");
}
isShouldSub = true;
condition.signal();
}
} finally {
System.out.println("主线程解锁");
lock.unlock();
}
}
public void sub() throws InterruptedException {
try {
lock.lock();
if (!isShouldSub) {
System.out.println("子线程等待");
condition.await();
} else {
System.out.println("子线程锁上了!");
for (int j = 0; j < 10; j++) {
System.out.println("子线程第" + j + "次");
}
isShouldSub = false;
condition.signal();
}
} finally {
System.out.println("子线程解锁");
lock.unlock();
}
}
}
}