案例一:两个线程交替打印1-100
public class PrintOneHundred {
public static void main(String[] args) {
Number number=new Number();
Thread th1=new Thread(number,"线程一");
Thread th2=new Thread(number,"线程二");
th1.start();
th2.start();
}
}
class Number implements Runnable{
private int i=0;
@Override
public void run() {
while(true) {
synchronized (this) {
notify();
if(i<100) {
i++;
System.out.println(Thread.currentThread().getName()+"---"+i);
}else {
break;
}
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
生产者消费者问题
public class ProducerAndConsumer {
private final int MAX_LEN=10;
private Queue<Integer> queue=new LinkedList<Integer>();
class Producer extends Thread{
@Override
public void run() {
producer();
}
public void producer() {
while(true) {
synchronized (queue) {
while(queue.size()==MAX_LEN) {
queue.notify();
System.out.println("当前队列满");
try {
queue.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(1);
queue.notify();
System.out.println("生产者生产一条任务,当前队列长度为"+queue.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class Consumer extends Thread{
@Override
public void run() {
consumer();
}
public void consumer() {
while(true) {
synchronized (queue) {
while(queue.size()==0) {
queue.notify();
System.out.println("当前队列为空");
try {
queue.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.poll();
queue.notify();
System.out.println("消费者消费一条任务,当前队列长度为"+queue.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
ProducerAndConsumer pc=new ProducerAndConsumer();
Producer producer=pc.new Producer();
Consumer consumer=pc.new Consumer();
producer.start();
consumer.start();
}
}