通过线程模拟火车过程过山洞,五列火车过一个山洞,一个时间点只能有一列火车通过
每列火车通过时间是2秒钟
每列火车通过时间是2秒钟
import Homeday21.Tunnel;
public class Homework {
public static void main(String[] args) {
Tunnel tun =new Tunnel();
Thread t1 = new Thread(tun,"赵家的火车");
Thread t2 = new Thread(tun,"钱家的火车");
Thread t3 = new Thread(tun,"孙家的火车");
Thread t4 = new Thread(tun,"李家的火车");
Thread t5 = new Thread(tun,"周家的火车");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Tunnel implements Runnable{
private int num = 0;
public void run(){
Cross();
}
public synchronized void Cross(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
num++;
System.out.println(Thread.currentThread().getName()
+" 第"+num+"个过隧道");
}
}
用两个线程,一个输出1,一个输出A,要求先输出A,再输出1
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import Lock.PrintCaseThread;
import Lock.PrintNumThread;
import Lock.Printer;
public class Lock {
public static void main(String[] args) {
Printer printer = new Printer();
PrintNumThread t1 = new PrintNumThread(printer);
PrintCaseThread t2 = new PrintCaseThread(printer);
t1.start();
t2.start();
//t2.start();如果要求先输出1,再输出A
//t1.start();
}
}
//打印数字的线程类
class PrintNumThread extends Thread{
private Printer printer;
public PrintNumThread(Printer printer) {
this.printer = printer;
}
@Override
public void run() {
printer.printNum();
}
}
//打印字母的线程类
class PrintCaseThread extends Thread{
private Printer printer;
public PrintCaseThread(Printer printer) {
this.printer = printer;
}
@Override
public void run() {
printer.printCase();
}
}
//可以用来打印数字,字母
class Printer{
//标记printCase方法是否执行
private boolean flag = false;
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
//打印数字
//在方法上加synchronized:表示想执行这个方法的当前对象解锁
public void printNum() {
//如果这个方法先进入,等一等,等到A打印完再继续
lock.lock();
try {
if(!flag) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i <= 26; i++) {
System.out.println(i);
}
}finally {
lock.unlock();
}
}
//打印字母
public void printCase() {
lock.lock();
try {
flag = true;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (char c = 'A'; c < 'Z'; c++) {
System.out.println(c);
}
condition.signal();
}finally {
lock.unlock();
}
}
}