A preliminary study of Java multithreading

Source: Internet
Author: User
Tags ticket

has always wanted to write about multi-threaded things, since you can consolidate their knowledge, and can look at their own level of mastery, because has always felt that this is very interesting. Don't say much nonsense, into the subject.
Java Multi-threading, we first think of what is more. Process, Thread,runnable,start,run ...
then we'll start with them. Why do you think of the process? Thought has been multithreaded multi-process said. So what's the difference between them.
process: A process is the most basic independent unit of running a program and allocating resources to the operating system. Each process is independent of its own without special treatment.
thread: Threads cannot exist independently, threads must be attached to processes, threads share the resources of processes, and in a sense, using threads is less expensive and more efficient.
in Java, there are two main ways to achieve multithreaded programming. One is to inherit the thread class, and one is to implement the Runnable interface. The difference between the two: I think the only
1.Runnable is more suitable for resource sharing between threads, and it is also recommended to use runnable.
2.Runnable is an interface so you can avoid the defects of thread single inheritance.
All right, this is just the mouth, let's take a look at the specific code.
Let's implement a classic window to buy tickets separately:
     inherited thread:
<span style= "FONT-SIZE:14PX;"    >class Salerthread extends thread{private int sum = 5;    public void Sale () {System.out.println (GetName () + "window is being sold, and" + (--sum) + "ticket is left.);        } @Override public void Run () {while (sum > 0) {sale (); }}}public class Testthread {public static void main (string[] args) {salerthread thread = new Salerthread ()        ;        Salerthread thread1 = new Salerthread ();        Salerthread thread2 = new Salerthread ();        Thread.setname ("1");        Thread1.setname ("2");        Thread2.setname ("3");        Thread.Start ();        Thread1.start (); Thread2.start ();}}    We can see the results, obviously not in accordance with our actual situation, but we change to achieve Runnable!class Salerrunnale implements runnable{private int sum = 5;    public void Sale () {System.out.println (Thread.CurrentThread (). GetName () + "window is being sold, with" + (--sum) + "ticket.");        } @Override public void Run () {while (sum > 0) {sale (); }}}public Class testthread {public static void main (string[] args) {Salerrunnale Runnale = new Salerrunnale ();        Thread thread = new Thread (Runnale, "1");        Thread thread1 = new Thread (Runnale, "1");        Thread thread2 = new Thread (Runnale, "1");        Thread.Start ();        Thread1.start ();    Thread2.start (); }}</span>


Two thread principals basically, that is, when calling the method in thread, we need to write one more step thread.currentthread.

Perhaps you want to ask, why do we call Start (), we can also call run (), I guarantee that the compiler will not error, and there are results, but the result is in accordance with the order we call the so-called thread output.


You might think, hum, it's just a coincidence, but when we call it multiple times, the result remains the same. Well, in fact, when calling the run () method directly, the JVM simply calls it as a normal method and does not reassign a thread to him. So be sure to remember that when you write a new thread, it is called the start () method, not the run () method that we rewrote.

Okay, now, let's talk about some of the states of multithreading:
Threads can have 6 states:
*new (newly created)
*runnable (can be run)
*blocked (blocked)
*waiting (blocked)
*timed Waiting (timed Wait)
*terminated (terminated)
Excerpt from: http://my.oschina.net/mingdongcheng/blog/139263)
Threads have their own priorities, and believe the word you should be familiar with. By default, child threads are the priority of inheriting parent threads, and of course, you can also set the priority by calling the SetPriority method. The priority of the thread should be min_priority (defined as 1 in thread) to max_priority (defined in thread as 10).
With the JVM default is to first call the priority high thread, the default is Norm_priority (thread in the definition of 5), when we call yield () in the thread, it will make the current threads in a state of concession, that is, first let not lower their own program first run, if there is no higher than their own, Still running on its own. Of course it's not absolute, he relies on operating system support.

There is a thread called a daemon thread. As the name implies, he needs to be guarded, if only he himself is meaningless. So, he doesn't exist on his own. Call them very simple. You only need to call Setdeamon (true) before start ().
However, he is still flawed, and the daemon should not access intrinsic resources, such as files and databases, because he will be interrupted at any time, even in the middle of an operation.


We run in one thread to half want to stop him what to do. Java started with the Stop method, but was deprecated because he was insecure. Not only that, Java also provides a method for thread hang methods suspend and wake-up methods for resume. But suspend can easily lead to deadlocks, so it has been abandoned.
But what if we need to pause a thread.
We can set a Boolean value.
such as private Boolean running;
Time to pause.
Public synchronized void Stop () {
running = false;
}
And we're in the Run method if running's condition is judged
while (running) {
Your code ...
}
Thus, we have implemented our own method of suspending. Of course, you might ask why you want to add synchronized, what does he mean? This is a question we will introduce later, of course, you can also look at the blog I wrote earlier---hyperlink---。

Well, to this, we also need to say the interruption of a thread. The thread terminates when the thread finishes executing the last statement of the Run method, or if there is an uncaught exception. Of course, we can call the interrupt method to terminate the thread. Each thread has a Boolean value that represents the interrupt state. Each thread should check this flag bit from time to times, and of course, if the thread has called wait,sleep or join before calling it, his interrupt status will be cleared and a InterruptedException . Exception will be thrown.

Thread also has a join method that calls another thread B in one thread A, and thread B calls join, and threads a waits for thread B to finish. Or call the join's overloaded method, and set the time to indicate how long to wait.

<span style= "FONT-SIZE:14PX;" ><span style= "FONT-SIZE:12PX;" >class Runnablea implements runnable{    @Override public    void Run () {for        (int i = 0; i < 5; i++) {            Sys Tem.out.println ("Threada:" + i);}}    } public class Testforjoin {public    static void Main (string[] args) throws interruptedexception {        Runnablea runnabl EA = new Runnablea ();        Thread Threada = new Thread (Runnablea);        Threada.start ();//        Threada.join ();        for (int i = 0; i < 5; i++) {            System.out.println (Thread.CurrentThread (). GetName () + ":" + i);}}    } </span></span>
when we comment on the Threada.join (), the result:

When we uncomment:

If it is a separate two thread, one thread calls the join and does not work on another thread.

<span style=" FONT-SIZE:14PX; " ><span style= "FONT-SIZE:12PX;" >public class Testforjoin {public static void main (string[] args) throws interruptedexception {Runnablea ru        Nnablea = new Runnablea ();        Thread Threada = new Thread (Runnablea, "Threada");        Thread threadb = new Thread (Runnablea, "threadb");        Threada.start ();        Threadb.start ();        Threada.join ();        for (int i = 0; i < 5; i++) {System.out.println (Thread.CurrentThread (). GetName () + ":" + i); }}}</span></span> 
Because calling another thread in a thread a b,b thread calls join, this only blocks the a thread, and if there is a thread at the same time, C,c can still preempt the CPU with B.
We said that the resources between the threads out of their own variable methods, the rest are shared, so, multithreading is bound to produce multiple threads simultaneously modify a block of memory problem. How can we avoid that?
The simplest and most effective method is, of course, not using multithreading. But what do we do when we have to use multithreading?
We first make a small program, multi-threaded in order to print 1-9, requires printing first 1-3, in print 4-6, the final output.
<span style= "FONT-SIZE:14PX;" ><span style= "FONT-SIZE:12PX;"    >public class Threadprint {static lock lock = new Reentrantlock ();    static Condition Reachthree = Lock.newcondition ();    static Condition Reachsix = Lock.newcondition ();        public static void Main (string[] args) {final int[] integer = {0}; Thread Threada = new Thread (new Runnable () {@Override public void run () {Lock.lock (                );                    try {for (int i = 1; I <= 3; i++) {System.out.println (i);                    } integer[0] = 3;                Reachthree.signal ();                } finally {Lock.unlock ();        }            }        }); Thread threadb = new Thread (new Runnable () {@Override public void run () {Lock.lock (                ); try {while (integer[0]! = 3) {ReaChthree.await ();                    } for (int i = 4; I <= 6; i++) {System.out.println (i);                    } integer[0] = 6;                Reachsix.signal ();                } catch (Interruptedexception e) {} finally {Lock.unlock ();        }            }        }); Thread THREADC = new Thread (new Runnable () {@Override public void run () {Lock.lock (                );                    try {while (integer[0]! = 6) {reachsix.await ();                    } for (int i = 6; I <= 9; i++) {System.out.println (i);                } integer[0] = 9;                } catch (Interruptedexception e) {} finally {Lock.unlock ();        }            }        });        Threada.start ();   Threadb.start ();     Threadc.start (); }}</span></span>

Lock is a locking mechanism provided to us in concurrent, when a thread enters a class, it is locked, and when there are other threads that have not exited before the thread is requested, the class is blocked until the first incoming thread exits and unlocks. Condition is a condition in which a lock can have one or more conditions. When a thread is blocked because of a condition, it automatically releases its lock, while another thread enters and wakes it. The lock Reentrantlock We call is a reentrant lock, but when a thread enters a class and calls a method with a lock, its counter is incremented by 1, minus one when a lock is released. Each time another thread enters the class, it checks to see if the counter is 0. We can also set it to fair lock new Reentrantlock (True) when the constructor is called, that is, the longer the wait time is likely to acquire the lock, but its efficiency is much lower than the unfair lock, so it is not necessary to use it. We always use the default unfair lock.
Of course, there is also a reentrantreadwritelock, when the thread frequently reads the data, he is a good choice, it has a read lock and write lock, it allows multiple threads to read, a specified number of threads to write operations. So the efficiency is high. The reentrantreadwritelock.readlock is used for each read operation, and the write operation is Reentrantreadwritelock.
Of course, Java also provides a more simple mechanism synchronized, you can set the synchronization block and synchronization method, specifically, you can refer to my other blog post: a preliminary discussion of Java objects wait (), notify (), Notifyall () And the synchronized in the thread. What needs to be said is that the synchronized call is actually an internal lock that contains only one condition.
You will think when to use synchronized when to use the lock.
1. In fact, it is best not to use two, because in our concurrent package, there is a synchronization queue, he will automatically help us to deal with the synchronization of data problems.
2. If synchronized is able to meet our requirements, use it as much as possible.
3. When we need to use the special features of Lock/condition, consider using it.

A preliminary study of Java multithreading

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.