For this reason, let's say that there are three windows at the train station , with a total of 5 tickets in the train ticket. Each thread is equivalent to a window that sells tickets separately
<strong>package com.thread;class myThread extends thread{private int ticketscount=5;//a 5-ticket private String name ;//window, that is, the name of the thread public MyThread (String name) {this.name=name;} @Overridepublic void Run () {while (ticketscount>0) {//ticketscount--;//If there is a ticket, sell a System.out.println (name+ "with" + ticketscount+ "Ticket, sold 11 tickets, the remaining votes:" +--ticketscount),//system.out.println (name+ "sold 11 tickets, the remaining votes:" +ticketscount);}} public class Ticketstread {public static void main (String args[]) {//Create three threads, simulate three windows sell tickets myThread t1=new myThread ("Window 1"); MyThread t2=new myThread ("Windows 2"); MyThread t3=new myThread ("Windows 3");//Start these three threads, which is the window to start selling tickets t1.start (); T2.start (); T3.start ( );}} </strong>
The output is:
The result shows that each window (thread) sells 5 tickets because it creates 3 thread objects, each with its own member instance variable.
Because each thread, MT1,MT2,MT3 is an object that inherits the thread class, the object has a private or common member variable or member method of its owning class, that is, their variable, that is, the number of votes Ticketcount is each object "own" private, " Each is a battalion, and the resources are not shared. Well, you'll see that every window has 5 tickets in the picture.
Use runnable again to implement this example.
Package Com.thread;class mythread_runnable implements Runnable{private int ticketscount=5;//a 5-ticket public void run () {// If you lock the Run method, a window will appear selling all the tickets while (ticketscount>0) {ticketscount--;//If there is a ticket, sell a System.out.println ( Thread.CurrentThread (). GetName () + "sold 11 tickets, remaining votes:" +ticketscount);}} public class Ticketsrunnable {public static void main (String args[]) {mythread_runnable mt=new mythread_runnable ();// Create three threads to simulate three ticket window thread t1=new thread (MT, "Window 1"); Thread T2=new Thread (MT, "Window 2"); Thread T3=new Thread (MT, "Windows 3");//Start these three threads, which is three windows, start selling tickets t1.start (); T2.start (); T3.start ();}}
The above is a special case where the thread (window) 11 times uses the CPU and executes all the code of the Run method, and then the process ends.
The following is a general result:
Above this output can be seen, thread resource rob caused by cross-execution.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Multi thread thread VS Runnable "with Case"