创建使用多线程的 三种方式
范例:,三售票同时卖票
方式一:内部类继承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();
}
本文来自博客园,作者:HumorChen99,转载请注明原文链接:https://www.cnblogs.com/HumorChen/p/10550204.html