多线程:
package cn.itheima.thread;
/*
* 1.多线程实现,输出线程自己的名字,并阻塞300毫秒,共输出20次
*/
public class Test1 {
public static void main(String[] args) {
Thread t=new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<20;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.start();
}
}
package cn.itheima.thread;
/*
* 2.定义一个类实现Runnable接口,卖票100张,四个线程,输出格式为“Thread-1,还剩10张票”
*/
public class Test2 {
public static void main(String[] args) {
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
Thread t4=new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
package cn.itheima.thread;
public class Ticket implements Runnable{
private static int ticket=100;
private boolean flag=true;
@Override
public void run() {
if (flag) {
while(true){
synchronized (Ticket.class) {
if (ticket>0) {
System.out.println(Thread.currentThread().getName()+":"+ticket--);
}
}
}
}else {
while(true){
this.show();
}
}
}
private synchronized void show() {
if (ticket>0) {
System.out.println(Thread.currentThread().getName()+":"+ticket--);
}
}
}
package cn.itheima.thread;
/*
* 3.编写三个类 Tocket 、 SealWindow TickerSealCener 分别代表票信息、售票窗口
售票中心。售票中心分配一定数量的票,由若干个窗口进行出售。来模拟卖票
*/
public class TesTickerSealCenert {
public static void main(String[] args) {
SealWindow sell=new SealWindow();
Thread t1=new Thread(sell);
Thread t3=new Thread(sell);
Thread t2=new Thread(sell);
t1.start();
t3.start();
t2.start();
}
package cn.itheima.thread;
public class Tocket {
private static int ticket=100;
public static void show(){
if (ticket>0) {
System.out.println(Thread.currentThread().getName()+":"+ticket--);
}
}
}
package cn.itheima.thread;
public class SealWindow implements Runnable{
private boolean flag=true;
@Override
public void run() {
if (flag) {
while(true){
synchronized (Tocket.class) {
Tocket.show();
}
}
}
}
}
|
|