题目: 有三个线程分别负责打印数字,按照如下规律打印:
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Thread3: 11
Thread3: 12
Thread3: 13
Thread3: 14
Thread3: 15
Thread1: 16
Thread1: 17
Thread1: 18
Thread1: 19
Thread1: 20
Thread2: 21
Thread2: 22
Thread2: 23
Thread2: 24
Thread2: 25
新建打印类:
package com.yf.service;
/**
File: Printer.java
Description: 打印服务类
@author
@date 2016年10月21日 下午2:14:46
@version 1.0
**/
public class Printer {
private int printNum = 1;
private int lock = 0;
synchronized public void print1() throws Exception{
while(printNum<=75){
if(lock != 0){
wait();
}else{
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ": " + printNum);
printNum ++;
}
//Thread.sleep(2000);
lock = 1;
notifyAll();
}
}
}
synchronized public void print2() throws Exception{
while(printNum<=75){
if(lock != 1){
wait();
}else{
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ": " + printNum);
printNum ++;
}
//Thread.sleep(2000);
lock =2;
notifyAll();
}
}
}
synchronized public void print3() throws Exception{
while(printNum<=75){
if(lock != 2){
wait();
}else{
for(int i=0;i<5;i++){
System.out.println(Thread.currentThread().getName() + ": " + printNum);
printNum ++;
}
//Thread.sleep(2000);
lock = 0;
notifyAll();
}
}
}
}
新建3个线程类:
public class Thread1 implements Runnable{
private Printer printer;
public Thread1(Printer printer) {
super();
this.printer = printer;
}
@Override
public void run() {
try {
printer.print1();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Thread2 implements Runnable {
private Printer printer;
public Thread2(Printer printer) {
super();
this.printer = printer;
}
@Override
public void run() {
try {
printer.print2();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Thread3 implements Runnable{
private Printer printer;
public Thread3(Printer printer) {
super();
this.printer = printer;
}
@Override
public void run() {
try {
printer.print3();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
新建测试调用:
Printer printer1 = new Printer();
Thread thread1 = new Thread(new Thread1(printer1));
thread1.setName("Thread1");
thread1.start();
Thread2 runnable = new Thread2(printer1);
Thread thread2 = new Thread(runnable);
thread2.setName("Thread2");
thread2.start();
Thread3 runnable3 = new Thread3(printer1);
Thread thread3 = new Thread(runnable3);
thread3.setName("Thread3");
thread3.start();
通过控制lock锁来达到依次调用print输出