两个线程交替打印字符串
/**
* 实现Runnable接口方式
* @author love
*
*/
class demo implements Runnable{
int i = 10;
@Override
public void run() {
while(true) {
synchronized (this) {
notify();
if(i>0) {
System.out.println(Thread.currentThread().getName()+": "+i+" "+"hello World!");
i--;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
}
}
}
}
/**
* 继承Thread类方式
* @author love
*
*/
class demo2 extends Thread{
@Override
public void run() {
int suv = 10;
while(true) {
synchronized(demo2.class) {
demo2.class.notify();
if(suv>0) {
System.out.println(currentThread().getName()+"Hello World!");
suv--;
try {
demo2.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
break;
}
}
}
}
}
生产者与消费者问题
package com.tao.demo1;
/**
* 线程通信:经典例题:生产者/消费者问题
* @author love
*生产者(producer)将商品交给店员(Clerk),而消费者从店员处取走产品,
*店员处一次只能有固定数量的产品(如20)
*如果生产者试图生产更多的产品,店员会叫停;
*若店员有空位存储产品,则会通知生产者继续生产;
*如果店员处没有商品,则会通知消费者等待。
*
*分析:
*1、是否式多线程问题?是,生产者,消费者
*2、是否数据共享? 是,店员或产品
*3、如何解决线程安全问题?同步机制,有三种方法
*4、是否涉及线程通信?是
*
*/
class Clerk{
private int productCount = 0;
//生产者
public synchronized void ProduceProduct() {
if(productCount<20) {
productCount++;
System.out.println(Thread.currentThread().getName()+":正在生产第"+productCount+"个产品");
notify();
}else {
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费者
public synchronized void ConsumeProduct() {
if(productCount>0) {
System.out.println(Thread.currentThread().getName()+":正在消费第"+productCount+"个产品");
productCount--;
notify();
}else {
//等待
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer extends Thread{//生产者类
private Clerk clerk;
public Producer(Clerk clerk) {
this.clerk = clerk;
}
@Override
public void run() {
System.out.println(currentThread().getName()+":开始生产产品...");
while(true) {
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.ProduceProduct();
}
}
}
class Customer extends Thread{//消费者类
private Clerk clerk;
public Customer(Clerk clerk) {
this.clerk = clerk;
}
public void run() {
System.out.println(currentThread().getName()+":开始消费产品...");
while(true) {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.ConsumeProduct();
}
}
}
public class ProductAndCustomer {
public static void main(String[] args) {
Clerk clerk = new Clerk();
new Producer(clerk).start();
new Customer(clerk).start();
}
}