标签:
package com.tonyluis; class MyThread extends Thread{ private int ticketNum; private String name; public MyThread(String name,int ticketNum){ super("Thread:"+name);//线程名 this.name =name; this.ticketNum=ticketNum; } public void run(){ int tmp=this.ticketNum; String threadName = Thread.currentThread().getName(); for(int i =0;i<tmp;i++){ if(this.ticketNum>0){ System.out.println("ThreadName:"+threadName+" "+this.name+"剩余 "+(this.ticketNum--)); } } } } class MyThread1 implements Runnable{ private int ticketNum =10; public void run(){ int tmp=this.ticketNum; String threadName = Thread.currentThread().getName(); for(int i =0;i<tmp;i++){ if(this.ticketNum>0){ System.out.println("ThreadName:"+threadName+" "+"剩余 "+(this.ticketNum--)); } } } } public class TestThread { public static void main(String[] args) { new MyThread("窗口1",3).start(); new MyThread("窗口2",4).start(); new MyThread("窗口3",2).start(); MyThread1 mt = new MyThread1(); new Thread(mt,"窗口4").start(); new Thread(mt,"窗口5").start(); new Thread(mt,"窗口6").start(); } }
运行结果:
ThreadName:Thread:窗口3 窗口3剩余 2
ThreadName:Thread:窗口1 窗口1剩余 3
ThreadName:Thread:窗口2 窗口2剩余 4
ThreadName:Thread:窗口1 窗口1剩余 2
ThreadName:Thread:窗口3 窗口3剩余 1
ThreadName:Thread:窗口1 窗口1剩余 1
ThreadName:Thread:窗口2 窗口2剩余 3
ThreadName:Thread:窗口2 窗口2剩余 2
ThreadName:Thread:窗口2 窗口2剩余 1
ThreadName:窗口5 剩余 10
ThreadName:窗口4 剩余 9
ThreadName:窗口6 剩余 10
ThreadName:窗口4 剩余 7
ThreadName:窗口5 剩余 8
ThreadName:窗口4 剩余 5
ThreadName:窗口6 剩余 6
ThreadName:窗口4 剩余 3
ThreadName:窗口5 剩余 4
ThreadName:窗口4 剩余 1
ThreadName:窗口6 剩余 2
继承Thread一般是多个线程分别完成自己的任务,实现Runable可以实现多个线程共同完成一个任务,而Thread需要通过内部类进行实现,实现起来比较麻烦
详见:http://blog.csdn.net/yilip/article/details/8147027
接口中不能有构造函数,所以,当你使用接口的时候,没法通过使用构造函数来传递变量。
标签:
原文地址:http://www.cnblogs.com/tonyluis/p/5479695.html