创建使用多线程的 三种方式

范例:,三售票同时卖票

方式一:内部类继承Thread类

public class Demo2{
int ticket=100,count=0;
boolean right=false;
class MyThread extends Thread{
public void run()
{
while(true)
if(ticket>0) {
--ticket;
++count;
if(ticket+count==100)
right=true;
System.out.println(Thread.currentThread().getName()+"卖出一张票!剩余:"+ticket+"张票。已经卖出"+count+"张票!检查结果:"+right);
right=false;
}
else
break;
System.out.println("全部票已经卖完!");
}
}
public void sellTicket()
{
MyThread m1=new MyThread();
m1.setName("窗口1");
m1.start();
MyThread m2=new MyThread();
m2.setName("窗口2");
m2.start();
MyThread m3=new MyThread();
m3.setName("窗口3");
m3.start();
}
public static void main(String[] args) {
new Demo2().sellTicket();
}
}

 

方式二:实现Runnable接口

public class Demo1 {
Thread th1,th2,th3;
int ticket=1000,count=0;
boolean right=false;
class Mythread implements Runnable{
public void run()
{
while(true)
if(ticket>0) {
--ticket;
++count;
if(ticket+count==1000)
right=true;
System.out.println(Thread.currentThread().getName()+"卖出一张票!剩余:"+ticket+"张票。已经卖出"+count+"张票!检查结果:"+right);
right=false;
}
else
break;
System.out.println("全部票已经卖完!");
}
}
public  void demo1()
{
Mythread my=new Mythread();
th1=new Thread(my,"窗口1");
th2=new Thread(my,"窗口2");
th3=new Thread(my,"窗口3");
th1.start();
th2.start();
th3.start();
}
public static void main(String[] args) {
new Demo1().demo1();
}
}

方式三:内部Runnable

public class Innerrunnable {


Thread th1;
int ticket=100,count=0;
boolean right=false;
public void sellTicket()
{

th1=new Thread(new Runnable() {
public void run()
{
while(true)
if(ticket>0) {
--ticket;
++count;
if(ticket+count==100)
right=true;
System.out.println(Thread.currentThread().getName()+"卖出一张票!剩余:"+ticket+"张票。已经卖出"+count+"张票!检查结果:"+right);
right=false;
}
else
break;
System.out.println("全部票已经卖完!");
}},"窗口1");
th1.start();
}
public static void main(String[] args) {
new Innerrunnable().sellTicket();


}

转载于:https://www.cnblogs.com/HumorChen/p/10550204.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值