多线程的简单举例
这里以窗口卖票为例,一共有10张票、3个窗口,卖的票不能重、不能多。
多线程的基本实现有好几种方法,包括继承Thread类,实现Runnable接口,使用线程池等。
实际开发中一般会采用线程池,这里初学演示使用Runnable接口。
public class TicketRunnable implements Runnable {
private int ticket=10;
@Override
public void run() {
while (true){
synchronized (this){
if (ticket>0){
System.out.println(Thread.currentThread().getName()+":"+ticket);
ticket--;
}else {
break;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
调用这个方法
public class TicketRunnableMain {
public static void main(String[] args) {
TicketRunnable ticket = new TicketRunnable();
Thread ticket1 = new Thread(ticket, "窗口1");
Thread ticket2 = new Thread(ticket, "窗口2");
Thread ticket3 = new Thread(ticket, "窗口3");
ticket1.start();
ticket2.start();
ticket3.start();
}
}
显示结果如下
还可以增加线程的通信,例如只有两个窗口,交替卖票
public class TicketCommunicate implements Runnable {
private int ticket = 10;
@Override
public void run() {
while (true) {
synchronized (this) {
notify();
if (ticket > 0) {
System.out.println(Thread.currentThread().getName() + "--" + ticket);
ticket--;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
}
}
}
public class TicketCommunicateMain {
public static void main(String[] args) {
TicketCommunicate ticketCommunicate = new TicketCommunicate();
Thread thread1 = new Thread(ticketCommunicate);
Thread thread2 = new Thread(ticketCommunicate);
thread1.setName("窗口1");
thread2.setName("窗口2");
thread1.start();
thread2.start();
}
}
结果是交替卖票的