synchronized 实现
public class ThreadTest {
public boolean flag;
public class OddClass implements Runnable {
public ThreadTest t;
public OddClass(ThreadTest t) {
this.t = t;
}
@Override
public void run() {
int i = 1; //本线程打印奇数,则从1开始
while (i < 100) {
synchronized (t) {
if (!t.flag) {
System.out.println("奇数:" + i);
i += 2;
t.flag = true;
t.notify();
} else {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class EvenClass implements Runnable {
public ThreadTest t;
public EvenClass(ThreadTest t) {
this.t = t;
}
@Override
public void run() {
int i = 2;
while (i <= 100)
synchronized (t) {
if (t.flag) {
System.out.println("偶数:" + i);
i += 2;
t.flag = false;
t.notify();
} else {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
ThreadTest tt = new ThreadTest();
OddClass jiClass = tt.new OddClass(tt);
EvenClass ouClass = tt.new EvenClass(tt);
new Thread(jiClass).start();
new Thread(ouClass).start();
}
}
ReentrantLock 实现
public class ThreadTest2 {
public boolean flag;
private Lock lock = new ReentrantLock();
private final Condition isEven = lock.newCondition();// 偶数
private final Condition isNotEven = lock.newCondition();// 奇数
public class OddClass implements Runnable {
public ThreadTest2 t;
public OddClass(ThreadTest2 t) {
this.t = t;
}
@Override
public void run() {
int i = 1; // 本线程打印奇数,则从1开始
while (i < 100) {
lock.lock();
if (!t.flag) {
System.out.println("奇数:" + i);
i += 2;
t.flag = true;
isNotEven.signal();
} else {
try {
isEven.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.unlock();
}
}
}
public class EvenClass implements Runnable {
public ThreadTest2 t;
public EvenClass(ThreadTest2 t) {
this.t = t;
}
@Override
public void run() {
int i = 2;
while (i <= 100) {
lock.lock();
if (t.flag) {
System.out.println("偶数:" + i);
i += 2;
t.flag = false;
isEven.signal();
} else {
try {
isNotEven.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.unlock();
}
}
}
public static void main(String[] args) {
ThreadTest2 tt = new ThreadTest2();
OddClass jiClass = tt.new OddClass(tt);
EvenClass ouClass = tt.new EvenClass(tt);
new Thread(jiClass).start();
new Thread(ouClass).start();
}
}
运行结果
奇数:1 偶数:0 奇数:3 偶数:2 奇数:5 偶数:4 奇数:7 偶数:6 奇数:9 偶数:8 奇数:11 偶数:10 奇数:13 偶数:12 奇数:15 偶数:14 奇数:17 偶数:16 奇数:19 偶数:18 奇数:21 偶数:20 奇数:23 偶数:22 奇数:25 偶数:24 奇数:27 偶数:26 奇数:29 偶数:28 奇数:31 偶数:30 奇数:33 偶数:32 奇数:35 偶数:34 奇数:37 偶数:36 奇数:39 偶数:38 奇数:41 偶数:40 奇数:43 偶数:42 奇数:45 偶数:44 奇数:47 偶数:46 奇数:49 偶数:48 奇数:51 偶数:50 奇数:53 偶数:52 奇数:55 偶数:54 奇数:57 偶数:56 奇数:59 偶数:58 奇数:61 偶数:60 奇数:63 偶数:62 奇数:65 偶数:64 奇数:67 偶数:66 奇数:69 偶数:68 奇数:71 偶数:70 奇数:73 偶数:72 奇数:75 偶数:74 奇数:77 偶数:76 奇数:79 偶数:78 奇数:81 偶数:80 奇数:83 偶数:82 奇数:85 偶数:84 奇数:87 偶数:86 奇数:89 偶数:88 奇数:91 偶数:90 奇数:93 偶数:92 奇数:95 偶数:94 奇数:97 偶数:96 奇数:99 偶数:98
网友评论