package xaincheng.printer;
public class Printer {
int i=1;
public synchronized void print(int num){
try {
if(i%3==0){
this.wait();
}
System.out.print(num);
i++;
this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void print(char c){
try {
if(i%3!=0){
this.wait();
}
System.out.print(c);
i++;
this.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package xaincheng.printer;
public class PrintA extends Thread{
Printer printer;
public PrintA(Printer printer){
this.printer = printer;
}
@Override
public void run() {
for(char i='A';i<='Z';i++){
printer.print(i);
}
}
}
package xaincheng.printer;
public class PrinterNum extends Thread{
Printer printer ;
public PrinterNum(Printer printer){
this.printer = printer;
}
@Override
public void run() {
for(int i=1;i<=52;i++){
printer.print(i);
}
}
}
package xaincheng.printer;
public class Test {
public static void main(String[] args) {
Printer printer =new Printer();
PrinterNum printerNum = new PrinterNum(printer);
PrintA printA = new PrintA(printer);
printerNum.start();
printA.start();
}
}
2、存钱
package xaincheng.atm;
public class Atm implements Runnable {
int nums = 20;
@Override
public void run() {
while (true) {
synchronized (this) {
if (nums <= 0) {
break;
}
nums--;
System.out.println(Thread.currentThread().getName() + ":取走1万元,卡里余额为" + nums + "万元");
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Atm atm = new Atm();
Thread th1 = new Thread(atm, "Atm1");
Thread th2 = new Thread(atm, "Atm2");
Thread th3 = new Thread(atm, "Atm3");
th1.start();
th2.start();
th3.start();
}
}
3、模拟挂号
package xaincheng.guahao;
public class MyRunable implements Runnable{
@Override
public void run() {
for(int i = 1;i<=10;i++){
System.out.println(Thread.currentThread().getName()+":专家号"+i+"号在看病");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package xaincheng.guahao;
public class Test {
public static void main(String[] args) {
MyRunable run = new MyRunable();
Thread thread = new Thread(run,"专家号");
thread.setPriority(10);
thread.start();
for(int i = 1 ;i<=50;i++){
System.out.println("普通号:普通号"+i+"在看病");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==10){
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}