基本方法
package com.meinvjianhao.thread;
public class ThreadDemo1 {
static volatile int num = 1;
static Object lock = new Object();
public static void main(String[] args) {
TestThread01 testThread01 = new TestThread01();
TestThread02 testThread02 = new TestThread02();
testThread01.testThread01();
testThread02.testThread02();
}
public static class TestThread01 {
public void testThread01() {
new Thread(() -> {
while (num < 100) {
synchronized (lock) {
while (num % 2 == 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "线程输出" + num++);
lock.notifyAll();
}
}
}).start();
}
}
public static class TestThread02 {
public void testThread02() {
new Thread(() -> {
while (num < 100) {
synchronized (lock) {
while (num % 2 != 0) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "线程输出" + num++);
lock.notifyAll();
}
}
}).start();
}
}
}
为什么使用while 而不使用if呢
防止虚假唤醒
使用线程池
package com.meinvjianhao.thread;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadDemo02 {
static volatile int num = 1;
static Object lock = new Object();
public static void main(String[] args) {
ThreadPoolExecutor pool =
new ThreadPoolExecutor(2,8,2,
TimeUnit.SECONDS,new ArrayBlockingQueue<>(10));
aa aa = new aa();
bb bb = new bb();
pool.execute(aa);
pool.execute(bb);
}
static class aa implements Runnable{
@Override
public void run() {
while (num < 100) {
synchronized (lock){
while (num % 2 ==0){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"线程"+num++);
lock.notifyAll();
}
}
}
}
static class bb implements Runnable{
@Override
public void run() {
while (num < 100) {
synchronized (lock){
while (num % 2 != 0){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"线程"+num++);
lock.notifyAll();
}
}
}
}
}