Java开发如何创建一个线程?
2个回答
2016-01-09 · 做真实的自己 用良心做教育
千锋教育
千锋教育专注HTML5大前端、JavaEE、Python、人工智能、UI&UE、云计算、全栈软件测试、大数据、物联网+嵌入式、Unity游戏开发、网络安全、互联网营销、Go语言等培训教育。
向TA提问
关注
展开全部
(1)通过扩展Thread类来创建多线程
public static void main(String [] args){
MutliThread m1=new MutliThread("Window 1");
MutliThread m2=new MutliThread("Window 2");
MutliThread m3=new MutliThread("Window 3");
m1.start();
m2.start();
m3.start();
}
}
class MutliThread extends Thread{
private int ticket=100;//每个线程都拥有100张票
MutliThread(String name){
super(name);//调用父类带参数的构造方法
}
public void run(){
while(ticket>0){
System.out.println(ticket--+" is saled by "+Thread.currentThread().getName());
}
}
}
(2)通过实现Runnable接口来创建多线程
public static void main(String [] args){
MutliThread m1=new MutliThread("Window 1");
MutliThread m2=new MutliThread("Window 2");
MutliThread m3=new MutliThread("Window 3");
Thread t1=new Thread(m1);
Thread t2=new Thread(m2);
Thread t3=new Thread(m3);
t1.start();
t2.start();
t3.start();
}
}
class MutliThread implements Runnable{
private int ticket=100;//每个线程都拥有100张票
private String name;
MutliThread(String name){
this.name=name;
}
public void run(){
while(ticket>0){
System.out.println(ticket--+" is saled by "+name);
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |