Java Multithreading-instance parsing

Source: Internet
Author: User

Java Multi-threaded instances 3 ways to implement
There are three ways to implement multithreading in Java:
1. Inherit the thread class, overriding the Run method. Thread is essentially an instance of runnable that represents an instance of a thread, and the only way to start a thread is through the thread class's Start method.
2. Implement the Runnable interface and implement the run () method of the interface. Creates a thread object that instantiates the thread object as a parameter with an object that implements the Runnable interface, and invokes the Start method of this object.
3. Implement the callable interface and override the call method. The callable interface is similar to the Runnable interface, but provides more powerful functionality than runnable. Have the following three points
1). Callable can provide a return value after the end of the character, Runnable does not provide this functionality.
2). The call method in callable can throw an exception, and the runnable run method cannot throw an exception.
3). Run callable you can get a future object that represents the result of an asynchronous calculation and provides a way to check whether the calculation is complete.

It is important to note that no matter how many threads are implemented in that way, invoking the Start method does not mean executing multithreaded code immediately, but rather making the thread operational.

the difference between run start
The Start method is to start a thread, and the Run method in the thread completes the actual operation.
If the developer calls the Run method directly, the method is called as a normal function, and there is no more threading, and if the developer wants multithreading to execute asynchronously, the Start method needs to be called.

The difference between sleep wait
1. The mechanism for dealing with the two is different, the sleep method is mainly to allow the thread to pause for a period of time, time to automatic recovery, and will not release the occupied lock, when the wait method is called, he will release the occupied object lock, waiting for other threads to call the Notify method to wake up again.
2.sleep is a static method of Threa, which is used to control the process of the thread itself, and wait is the method of object, which is used for thread communication.
3. The areas used are different. Sleep can be used anywhere, and wait must be performed in a synchronous control method or in a statement block.


the use of synchronized notify wait
The Synchronized keyword has two usages, the synchronized method, and the synchronized block of statements.
Public synchronized void function () {}
Synchronized (object) {}
When a resource is modified by synchronized, thread 1 thread 2 and many other threads are requesting the resource together, thread 1 requests It first, the wait method that called the object frees the object's lock, and thread 2 can access the object, and at the end of the work, the object's Notify method can be called. Wakes the waiting thread in the wait queue, at which point the awakened thread will once again get the object lock and manipulate the object. You can call the Notifyall method to wake up all the threads in the waiting queue.

It is important to note that a thread being awakened does not represent an immediate acquisition of an object lock, it must wait for the calling thread object's method to eject the synchronized block after the object lock is released, and the awakened process acquires the object lock.

Here's a simple example of code for you:

The runnable and thread methods are used respectively to show the various methods of

Implementation of multi-threading method for runnable

 Public classTestrunnableImplementsRunnable {Private intTime=1; PrivateSourcea S; PrivateString id = "001";  Publictestrunnable (Sourcea s) { This. S =s; }     Public voidSetTime (intTime ) {         This. Time =Time ; } @Override Public voidrun () {Try{System.out.println ("I'll Sleep" +Time );        Thread.Sleep (time); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }        synchronized(s) {s.notify (); System.out.println ("I woke up 002!" "); System.out.println ("I deposited the ID" +ID);        S.setsource (ID); }    }}

The method of inheriting thread to implement multithreading

 Public classTestthreadextendsThread {Private intTime = 1; PrivateSourcea s =NULL; String ID= "002";  Public voidSetTime (intTime ) {         This. Time =Time ; }         PublicTestthread (Sourcea s) { This. S =s; } @Override Public voidrun () {Try{System.out.println ("I'll Sleep" +Time );        Sleep (time); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }                synchronized(s) {Try{System.out.println ("I" + ID + "to wait");            S.wait (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.println ("I was awakened."); System.out.println ("I deposited the ID" +ID);        S.setsource (ID); }    }}

Sourcea Class Code:

 Public class sourcea {    privatenew arraylist<string>();      Public synchronized void GetSource () {        for (int i=0;i<list.size ();i++) {            System.out.println (List.get (i));        }    }      Public synchronized void SetSource (String id) {        list.add (id);}    }

Test Class Code:

 Public void Test () {        new  sourcea ();         New Testthread (s);         New testrunnable (s);         New Thread (TR);        System.out.println ("Call thread 1");        Tt.start ();        System.out.println ("Call thread 2");        T.start ();    }

Result Picture:

Java Multithreading-instance parsing

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.