Java多线程经典案例
1.三个售票窗口同时出售20张票
public class Demo1
{
public static void main(String[] args)
{
TicketOffice ticketOffice = new TicketOffice(new Object(), 20);
new Thread(ticketOffice, "窗口1").start();
new Thread(ticketOffice, "窗口2").start();
new Thread(ticketOffice, "窗口3").start();
}
}
class TicketOffice implements Runnable
{
private Object object;
private int ticketNum;
public TicketOffice(java.lang.Object object, int ticketNum)
{
this.object = object;
this.ticketNum = ticketNum;
}
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();
}
}
}
}
}
}
2.创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D ...
public class Demo2
{
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;
}
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;
}
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();
}
}
}
}
}
}
3.
启动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. 程序的输出结果应该为:
线程1: 1
线程1: 2
线程1: 3
线程1: 4
线程1: 5
线程2: 6
线程2: 7
线程2: 8
线程2: 9
线程2: 10
…
线程3: 71
线程3: 72
线程3: 73
线程3: 74
线程3: 75
public class Demo3
{
public static void main(String[] args)
{
Object object = new Object();
new Thread(new PrintRunnable(object,1)).start();
new Thread(new PrintRunnable(object,2)).start();
new Thread(new PrintRunnable(object,3)).start();
}
}
class PrintRunnable implements Runnable
{
private static volatile int printNum = 0;
private Object object;
private int threadId;
public PrintRunnable(Object object, int threadId)
{
super();
this.object = object;
this.threadId = threadId;
}
public void run()
{
while (printNum < 75)
{
synchronized (object)
{
if (printNum / 5 % 3 + 1 == threadId)
{
for (int i = 0; i < 5; i++)
{
System.out.println("线程" + threadId + ":" + (++printNum));
}
object.notifyAll();
}
else
{
try
{
object.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
}
原文地址https://blog.csdn.net/xixiangdeshaonian/article/details/82228492