1、创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D
public class Problem01 {
public static void main(String[] args) {
Object object = new Object();
new Thread(new Number(object)).start();
;
new Thread(new Character(object)).start();
;
}
}
class Number implements Runnable {
private Object object;
public Number(Object object) {
this.object = object;
}
@Override
public void run() {
synchronized (object) {
for (int i = 1; i < 53; i++) {
if (i > 1 && i % 2 == 1) {
System.out.print(" ");
}
System.out.print(i);
if (i % 2 == 0) {
// 先释放锁,唤醒其他线程,再使本线程阻塞
object.notifyAll();
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Character implements Runnable {
private Object object;
public Character(Object object) {
this.object = object;
}
@Override
public void run() {
synchronized (object) {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.print(i);
// 先释放锁,唤醒其他线程,再使本线程阻塞
object.notifyAll();
if (i < 'Z') { // 线程执行的最后一次不能堵塞,不然会一直堵塞下去。
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
2、启动3个线程打印递增的数字, 线程1先打印1,2,3,4,5 然后是线程2打印6,7,8,9,10 然后是线程3打印11,12,13,14,15.接着再由线程1打印16,17,18,19,20....以此类推, 直到打印到75。
public class Problem02 {
public static void main(String[] args) {
final Hander hander = new Hander();
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for(int j=0;j<5;j++) {
hander.print(Thread.currentThread().getName());
}
}
}, i + "").start();
}
}
}
class Hander {
private int no = 1;
private int status = 0;
// 将该方法上锁
public synchronized void print(String threadName) {
int threadIndex = Integer.parseInt(threadName);
while (threadIndex != status) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("Thread-"+threadName+" : ");
for (int count = 0; count < 5; count++, no++) {
if (count > 0) {
System.out.print(",");
}
System.out.print(no);
}
System.out.println();
status = (status + 1) % 3;
this.notifyAll();
}
}
3、三个售票窗口同时出售20张票。
public class Problem03 {
public static void main(String[] args) {
TicketOffice ticketOffice = new TicketOffice(new Object(), 20);
new Thread(ticketOffice, "ticket-1").start();
new Thread(ticketOffice, "ticket-2").start();
new Thread(ticketOffice, "ticket-3").start();
}
}
class TicketOffice implements Runnable {
private Object object;
private int ticketNum;
public TicketOffice(Object object, int ticketNum) {
this.object = object;
this.ticketNum = ticketNum;
}
@Override
public void run() {
while (ticketNum > 0) {
synchronized (object) {
if (ticketNum <= 0) {
System.out.println(Thread.currentThread().getName() + " : 没有票啦...");
} else {
System.out.println(Thread.currentThread().getName() + " : 卖出了第" + ticketNum-- + "张票");
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}