线程的两种创建方式与火车售票demo_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 线程的两种创建方式与火车售票demo

线程的两种创建方式与火车售票demo

 2015/2/6 13:02:42  operating...mydream  程序员俱乐部  我要评论(0)
  • 摘要:1.继承Thread类,重写run方法创建形式如下:publicclassMyThreadextendsThread{privateinttimes=5;privateStringname;publicMyThread(Stringname){this.name=name;}@Overridepublicvoidrun(){while(times>0){times--;System.out.println(name+"售出一张票:"+times);}}
  • 标签:创建 方式 线程
class="java">?1.继承Thread类,重写run方法
?创建形式如下:
public class MyThread extends Thread {
	private int times = 5 ; 
	private String name;
	
	public MyThread(String name){
		this.name = name;
	}

	@Override
	public void run() {
		while(times > 0){
			times--;
			System.out.println(name + "售出一张票:" + times);
		}
	}
	
}

?

public class TestThread {

	public static void main(String[] args) {
		
		MyThread trd1 = new MyThread("窗口一");
		MyThread trd2 = new MyThread("窗口二");
		MyThread trd3 = new MyThread("窗口三");
		
		trd1.start();
		trd2.start();
		trd3.start();
		
	}
}

?

?2.实现Runnable接口,重写run方法

??? 实现形式如下:
public class MyRunnable implements Runnable { private int times = 5 ; @Override public void run() { while(times > 0){ times--; System.out.println(Thread.currentThread().getName() + "售出一张票:" + times); } } }

?

public class MyRunnable implements Runnable { 
  private int times = 5 ; 
  @Override 
  public void run() { 
    while(times > 0){ times--;
     System.out.println(Thread.currentThread().getName() + "售出一张票:" + times);
    } 
  } 
}

public class TestRunnable {
	public static void main(String[] args) {
		MyRunnable mrt1 = new MyRunnable();
		
		Thread t1 = new Thread(mrt1,"窗口一");
		Thread t2 = new Thread(mrt1,"窗口二");
		Thread t3 = new Thread(mrt1,"窗口三");
		
		t1.start();
		t2.start();
		t3.start();
	}
}

?

?

上一篇: 不站队的极路由选择加入了海尔U+联盟 下一篇: 没有下一篇了!
发表评论
用户名: 匿名