Package Com.tonyluis;class MyThread extends thread{private int ticketnum; private String name; Public MyThread (String name,int ticketnum) {super ("Thread:" +name);//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:" +thread Name+ "" +this.name+ "remaining" + (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:" +thread name+ "" + "remaining" + (this.ticketnum--)); }}}} public class Testthread {public static void main (String[] args) {New MyThread ("Window 1", 3). Start (); New MyThread ("Windows 2", 4). Start (); New MyThread ("Windows 3", 2). Start (); MyThread1 MT = new MyThread1 (); New Thread (MT, "Window 4"). Start (); New Thread (MT, "Window 5"). Start (); New Thread (MT, "Window 6"). Start (); } }
Operation Result:
Threadname:thread: Window 3 window 3 remaining 2
Threadname:thread: Window 1 window 1 remaining 3
Threadname:thread: Window 2 window 2 remaining 4
Threadname:thread: Window 1 window 1 remaining 2
Threadname:thread: Window 3 window 3 remaining 1
Threadname:thread: Window 1 window 1 remaining 1
Threadname:thread: Window 2 window 2 remaining 3
Threadname:thread: Window 2 window 2 remaining 2
Threadname:thread: Window 2 window 2 remaining 1
ThreadName: Window 5 remaining 10
ThreadName: Window 4 remaining 9
ThreadName: Window 6 remaining 10
ThreadName: Window 4 remaining 7
ThreadName: Window 5 remaining 8
ThreadName: Window 4 remaining 5
ThreadName: Window 6 remaining 6
ThreadName: Window 4 remaining 3
ThreadName: Window 5 remaining 4
ThreadName: Window 4 remaining 1
ThreadName: Window 6 remaining 2
Inheriting thread is generally the task of multiple threads to complete their own tasks, implementation of runable can implement multiple threads together to complete a task , and the thread needs to be implemented through the internal class, the implementation is more troublesome
See: http://blog.csdn.net/yilip/article/details/8147027
interfaces cannot have constructors, so when you use interfaces, you cannot pass variables by using constructors .
Java thread and runnable differences