OverviewThere are 2 common ways to implement multithreading:1. Inheriting the thread class2. Implement the Runnable interfaceThis is commonly used because multithreading can also be achieved through the thread pool in the Juc (java.util.concurrent) package. We'll go into details about the thread pool, and now we'll get to the thread and runnable.Thread IntroductionThread is a class. Thread itself implements the Runnable interface. It declares the following: Public class Implements Runnable {}The
mythread ("window Third");
Mt1.start ();
Mt2.start ();
Mt3.start ();
28.}
29.
30.}
The results of the operation are as follows:
Java Code
1. A window to sell tickets---->10
2. A window to sell tickets---->9
3. Window Second sells tickets---->10
4. A window to sell tickets---->8
5. A window to sell
. Do I have to get a new ticket every time I get an email? If so, I don't like your system.Athena: Ah... I don't understand why tickets cannot be reused. If I have obtained a ticket to the mail service, I can use it again and again. When the email client requests the service with your name, it transfers a copy of the ticket to the service.Euripides: better. But I still have problems. You seem to imply that every time I use a service without a ticket,
itself is a class that implements the Runnable interface. We know that "a class can have only one parent class, but it can implement multiple interfaces", so runnable has better extensibility.In addition, runnable can also be used for "sharing resources." That is, multiple threads are based on a single Runnable object, and they share resources on the Runnable object.Generally, it is recommended to implement multithreading through "Runnable"!
Thread and runnable examples of multithreading1. Thr
1. Put the EMU ticket and the Z-headed ticket 20 days later. At this time, generally no one will grab the EMU ticket (after all, the EMU will not be very popular ). However, some key lines (with large passenger flows, few vehicles, and the appropriate time) will be packed at this time with a considerable number. For example, z37 and z77, these two vehicles are delivered to direct buses in Wuchang and Hankou. They are arriving at the same time on the eve of the Day, and many hard sleeper trains a
Synchronized is used to lock a method or block, only the object that obtains the lock of the object or block can execute the code inside, otherwise it will block there, wait for the lock to be released, and then get the lock to continue execution. For example, the following code to simulate ticketing:/*** Simulated Sale tickets* * @author Administrator**/Public class Synchronizeddemo {Public static void Main (string[] args) {Runnable Runnable = new Ru
Today is still multi-threading, but before doing a practice, with multi-threaded mock cinema ticket sales, the problem: A movie theater is currently on the release of the Lunar New Day blockbuster (Red Sorghum, Shaolin Temple legend Sutra Pavilion), a total of 100 tickets, and it has 3 ticket window ticket, please design a program to simulate the cinema ticket sales.We know that there are two ways to implement threading, let's take a look at the first
Public void B (){
Synchronized (shared object ){
I ++;
}
}
Note: synchronization is a highly open operation, so you should minimize the amount of synchronization content. Generally, there is no need to synchronize the entire method. Use the synchronized code block to synchronize key code.
3. As mentioned above, we will go on to the ticket sales system in the previous article to add multiple windows to sell tickets, that is, to add multiple thread
(); Mt3.start (); } } The results of the operation are as follows:A window sells tickets---->10a window to sell tickets----GT;9window second, sell tickets .----GT;10a window to sell tickets----GT;8a window to sell tickets----GT;7a window to sell
The following is an example of a multi-thread ticket buying error:
Public class SaleTicketMutiThread implements Runnable {Int tickets = 100;Int temp = tickets;Boolean flag = true;@ OverridePublic void run (){While (flag ){If (tickets> 0 ){Try {Thread. sleep (30 );} Catch (InterruptedException e ){E. printStackTrace ();}Sale ();} Else {Flag = false;System. out. pr
First, look at two pieces of code.
By inheriting the thread class
classmythreadextendsthread{ privateintticket=10; private stringname; publicmythread (stringname) { this.name=name; } publicvoidrun () { for (inti=0;i
A window to sell tickets---->10 A window to sell tickets---->9 window second selling tickets----the window to sell
role, to achieve multithreading.
Similarities and differences of thread and runnable
Thread and Runnable the same point: are "multithreading implementation."
Different points of Thread and Runnable:
Thread is a class, and runnable is an interface; thread itself is a class that implements the Runnable interface. We know that "a class can have only one parent class, but it can implement multiple interfaces", so runnable has better extensibility.
In addition, runnable can also be used for "shari
creates an event object. Its function prototype is:Handle createevent (Lpsecurity_attributes lpeventattributes, // SDBool bmanualreset, // reset ype true indicates a manual reset event, and false indicates an automatic reset event object.Bool binitialstate, // The initial state has an accident. True indicates a signal state, and vice versa.Lptstr lpname // Object Name);Setevent is set to a signal state; resetevent is set to a non-signal state.(3) manually reset the event object//***************
The landlord of this article mainly to the user in the ticket Office purchase tickets for the background of multi-threaded implementation. Suppose a city to B city tickets Total 50, a total of 3 ticket window in the ticket, using multi-threading to simulate the ideal situation of the user purchase tickets:The ticket class for implementing runnable:1 package com.jon.thread; 2 3 public class Ticketsell impl
March 28 0:01 A.M., Shanghai Disneyland tickets are officially open for sale. The surging news experience found that the opening day tickets sold by Disney Online official channels were killed in seconds.Insiders analysis that the opening tickets to Shanghai Disneyland 16th was killed, on the one hand or because the day only opened half-day and there are large-sc
) {mythread Mt = new mythread (); Mt. getthread (). start (); Mt. getthread (). start (); While (true) {system. out. println ("Main:" + thread. currentthread (). getname ());}}}
3. Thread SynchronizationTwo synchronous Methods: Synchronous block and synchronous methodEach object has a monitor or lock.The synchronization method uses the lock of the object represented by this. The Class Object monitor of the class used for static method synchronization. Each class also has a lock, which is the loc
{ publicabstractvoid run ();}Thread is a class that implements the Runnable interface. For example: public class Thread implements Runnable {}We know that "a class can have only one parent class, but it can implement multiple interfaces", so runnable has better extensibility. In addition, runnable can also be used for "resource sharing". That is, multiple threads are based on aA Runnable object that shares the resources established on the Runnable object. It is generally recommended to impl
share the memory of the original process block. As a result, communication between threads is easy and fast. Because different processes are in different chunks of memory, communication between processes is relatively difficult. In Java, there are two ways to implement multithreading: Inherit the Java.lang.Thread class, and implement the Java.lang.Runnable interface.
third, inherit the thread class to realize multithreadingWhen a class inherits the thread class, the run () method must be
Static void Print(Object o) {System.out.println (o.tostring ()); }}The output is:Thread: Little Red, now there are 9 tickets!Thread: Little Red, now there are 6 tickets!Thread: Little blue, now there are 7 tickets!Thread: Little blue, now there are 4 tickets!Thread: Small green, now there are 8
controlThread synchronization through a mutex class
Thread synchronization control is implemented through the mutex class, and if you need a program variable at the same time for multiple line Chengzhong, you can lock the variable part with lock. The code is as follows:
#encoding: GBK
require "thread"
puts "Synchronize thread"
@num =200
@mutex =mutex.new
def Buyticket (num)
@mutex. Lock
if @num >=num
@num = @num-num
puts "you have successfully bought #{num}
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.