Anonymous inner class implements thread creation __java

Source: Internet
Author: User
Tags ticket
public class Main {public
	static void Main (string[] args) {for
		(int i=0;i<4;i++) {
			new Thread (New Runnable () {
				@Override public
				void Run () {
					for (int j=0;j<100;j++) {ticket.fun ()}}}
			, Window + (i+1)). Start ();}}

public class Ticket {
	static int a = 0;	
	Public synchronized static void Fun () {
		ticket.a++;
		System.out.println (Thread.CurrentThread (). GetName () + "is selling the first" +ticket.a+ "Ticket");
	}
The above code implements multiple threads to sell tickets at the same time, because A and fun () are shared resources, so with the lock, the thread must enter the lock that has to look at the thread to see if it is released or not. The new Runnable () {} above does not instantiate the Runnable interface, but instead instantiates an anonymous inner class that implements the Runnable interface, because it is anonymous, so you don't know what the name of the class is, if we write a class to implement the Runnable interface, Then we can replace the new Runnable () {} With this class that implements the Runnable interface, and of course the name class that implements the Runnable interface can write its own code in run (). If the class with the name implementation runnable and the anonymous inner class are written like run (), then the anonymous inner class will overwrite the class with the name.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.