1、使用生产者和消费者模式实现,交替输出:
假设只有两个线程,输出以下结果:
t1–>1
t2–>2
t1–>3
t2–>4
t1–>5
t2–>6
要求:必须交替,并且t1线程负责输出奇数。t2线程负责输出偶数。
两个线程共享一个数字,每个线程执行时都要对这个数字进行:++
实现思路:
设置生产者类,消费者类,数字类,主函数类。数字类为生产者和消费者共享。
1.主函数类
public class ProducerTest {
public static void main(String[] args){
Num n = new Num();
Thread t1 = new Producer(n);
t1.setName("t1");
Thread t2 = new Consumer(n);
t2.setName("t2");
t1.start();
t2.start();
}
}
2.生产者类
class Producer extends Thread{
Num n;
public Producer(){};
public Producer(Num n){
this.n = n;
}
@Override
public void run() {
while(true){
synchronized(n){
if (n.i%2==0){
try {
n.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
n.print();
n.notifyAll();
}
}
}
}
3.消费者类
class Consumer extends Thread {
Num n;
public Consumer() {
n.print();
}
public Consumer(Num n) {
this.n = n;
}
@Override
public void run() {
while(true){
synchronized(n){
if (n.i%2!=0){
try {
n.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
n.print();
n.notifyAll();
}
}
}
}
4.数字类
class Num{
int i = 1;
public Num(){}
public void print(){
System.out.println(Thread.currentThread().getName() + "----->"+ this.i++);
}
}
完整代码
package zuoye.day34;
public class ProducerTest {
public static void main(String[] args){
Num n = new Num();
Thread t1 = new Producer(n);
t1.setName("t1");
Thread t2 = new Consumer(n);
t2.setName("t2");
t1.start();
t2.start();
}
}
class Producer extends Thread{
Num n;
public Producer(){};
public Producer(Num n){
this.n = n;
}
@Override
public void run() {
while(true){
synchronized(n){
if (n.i%2==0){
try {
n.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
n.print();
n.notifyAll();
}
}
}
}
class Consumer extends Thread {
Num n;
public Consumer() {
n.print();
}
public Consumer(Num n) {
this.n = n;
}
@Override
public void run() {
while(true){
synchronized(n){
if (n.i%2!=0){
try {
n.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
n.print();
n.notifyAll();
}
}
}
}
class Num{
int i = 1;
public Num(){}
public void print(){
System.out.println(Thread.currentThread().getName() + "----->"+ this.i++);
}
}