Java Threads:

Source: Internet
Author: User

Thread:

Mode one: inherits the thread class and the replication run method.

Format:

Class MyThread extends Thread

{

public void Run ()

{

The code to run in the thread.

}

}

The steps are:

1. Define class inheritance for the thread class.

2. Review the Run method.----> Purpose is to store the code in the thread to run, store the custom code in the Run method, and let the thread run.

3. Call the thread's Start method

Note: The Run method is not called.

The name of the thread: the generic thread has the default name, in the form: thread-number, which is marked starting at 0.

You can also get the name of the currently running thread, using the method: Thread.CurrentThread (). GetName ()

Thread.CurrentThread () is the object used to get the current thread. (Static).

The name of the custom settings thread can be set using the SetName () or constructor.

Code examples and exercises about how threads are inherited:

View Code View Code
1/* 2 Ticket Window Example: More than 3 windows can sell tickets at the same time. 4 */5  6 class Ticket extends Thread 7 {8     private static int Ticket = 100;//No static time. Two windows will also sell the same number of tickets, that is, 100 tickets with a window Will be sold once (equivalent to sold 200 times) 9     Ticket (String name)     {One         super (name), and}13 public     Void Run (),     {15 While         (true)         {             if (ticket>0)                 System.out.println (Thread.CurrentThread (). GetName () + = = = = = = = = = = = = = = = = = = = = = ticket--),             }21         }22     }23}24, class TicketDemo27 {n-public     static void Main (String args[]) 29< c19/>{30         Ticket t1 = new Ticket ("Window 1"),         Ticket t2 = new Ticket ("Window 2"); T1.start (         );         T2.start ( );     }36}


The second way of threading:

Implement the Runnable interface:

The format is:

Class Myrunnable implements Runnable

{

public void Run ()

{

The code to run in the thread.

}

}

The steps are generally:

1. Define a class to implement the Runnable interface.

2. The Run method in the replication Runnable interface.

3. Create an object by using the thread class.

4. Pass the object of the Runnable subclass as the actual argument to the constructor in the thread class.

5. Call the Start method in the thread class. Turn on the thread and call the Run method of the subclass of the Runnable interface. (Can be understood as the Run method and the Start method to open the call)

For example:

Class Myrunnable implements Runnable//step 1

{

public void Run ()//Step 2

{

S.O.P ();

}

}

Class Runnabledemo

{

P.s.v.main ()

{

Myrunnable Mr = New Myrunnable ();

thread T1 = new Thread (MR); Step 3---4

T1.start (); Step 5

}

}

View Code

The differences and characteristics of the polymorphism of the way of inheritance and realization:

Implementation: Avoids the limitations of single inheritance. It is recommended to use implementations when threading is generally defined.

Difference:

1. Inherited thread: Thread code is stored in the Run method of the subclass of thread.

2. Implement Runnabel: The code of the thread is stored in the Run method of the subclass of the Runnable interface.

Finally, the synchronous code block solves the problem of multithreading security.

The format is:

Synchronized (object)

{

Blocks of code that need to be synchronized.

}

For examples and practice code to implement runnable interfaces and synchronizations:

 1/* 2 multi-threaded security issues; 3 printed out the number of votes for 0.-1.-2 and so on. 4 5 problem analysis, when multiple statements use the same thread shared data at the same time, one of the threads executes only part of it, and the other thread executes, causing errors in sharing the data. 6 in the If judgment, when Ticket=1 is executed, one thread goes in to execute the statement and the other thread comes in. 7 at this time the ticket has been ticket--into 0, resulting in a 0 or negative output votes.                     8 Solution: 9 The operation of multiple shared data statements, so that one thread completely completed before the execution of another thread, so as to avoid the occurrence of this problem. 10 11                         Synchronize code blocks. Keyword: synchronized12 format: Synchronized (object) 14 {15                     The code that needs to be synchronized. 16 {17 18 Conditions for synchronization: 19                     1. Must be multi-threaded, single thread cannot be synchronized. 20 2. You must use the same lock for multiple threads. 21 You must ensure that only one thread in the synchronization is running. 22  23 Benefits of synchronization: Resolves the security issue of multithreading. 24 Cons: Each thread must determine the lock, affect the program speed, the cost of resources. */26 class Ticket implements Runnable27 {private int Ticket = 100; Object obj = new Object (), and public void run () {+ (true) @ Synchron ized (obj)//oBJ is the equivalent of a lock. {ticket>0) PNs {//Try{thread.sleep (10 );}                 catch (Exception e) {}39 System.out.println (Thread.CurrentThread (). GetName () + "= = = Sell ticket =====" +ticket--); 40 }41}42}43}44}45-Class RunnableTicketSafeDemo47 {$ public static void Ma  In (String args[]) (Ticket t = new Ticket (); T is a shared data. The thread T1 = new Thread (t), the t2 thread = new Thread (t), and the T3 thread = new T Hread (t); t4 = new Thread (t), T1.start (), T2.start (); ; T4.start (); 61}62}

Java Threads:

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.