Java Basics Multi-Threading (2)

Source: Internet
Author: User

The sleep of a thread

How to use: public static void Sleep (long Millis) throws interruptedexception{}
It can be seen that the method has an exception thrown, so the exception to be handled.

 Public  class A implements Runnable {    PrivateString name; Public A(String name) {Super(); This. name = name; }@Override     Public void Run() {//TODO auto-generated method stub         for(inti =0; I <Ten; i++) {Try{Thread.Sleep ( -);//Hibernate}Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println ("Run:"+ name); }    }}

Test it:

publicclass ATest {    publicstaticvoidmain(String[] args) {        // TODO Auto-generated method stub        new A("线程1");        new A("线程2");        new Thread(mt1,"线程111").start();        System.out.println(Thread.currentThread().getName());        new Thread(mt2,"线程111").start();    }}
Priority of the thread
 Public  class mythreadimplement implements Runnable {    @Override     Public void Run() {//TODO auto-generated method stub         for(inti =0; I <5; i++) {Try{Thread.Sleep ( -);//Hibernate}Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); }//Get the current thread nameSystem.out.println (Thread.CurrentThread (). GetName ()); }    }}

Test class:

 Public classmythreadimplementtest { Public Static void Main(string[] args) {//TODO auto-generated method stubMythreadimplement MT1 =NewMythreadimplement (); Thread M1 =NewThread (MT1,"Thread 1"); Thread m2 =NewThread (MT1,"Thread 2"); Thread m3 =NewThread (MT1,"Thread 3");//Use the SetPriority () method to set thread priority        //The parameters passed in are constants in the thread class, each representing the highest priority, normal, and lowestM1.setpriority (thread.max_priority);        M2.setpriority (thread.norm_priority);        M3.setpriority (thread.min_priority);    M1.start (); M2.start (); M3.start (); }}
Interrupt of Thread

Call the interrupt () method to break a running thread!

Synchronization issues for Threads

Look at a small example:

 Public  class tickthread implements Runnable {    //Analog sell ticket, total 5 photos    Private intTick =5;@Override     Public void Run() {//TODO auto-generated method stub         for(inti =0; I <5; i++) {if( This.tick>0){Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println ("Sell ticket:"+tick--); }        }    }}

Test class:

publicclass TickThreadTest {    publicstaticvoidmain(String[] args) {        // TODO Auto-generated method stub        new TickThread();        new Thread(m,"A").start();        new Thread(m,"B").start();        new Thread(m,"C").start();    }}


An exception was found by running the result. The reason is that the code is added to the hibernation operation, thread A is sleeping, thread B runs up and sells the current thread A's ticket, a after the end of sleep, continue to sell tickets, the above situation appears. This problem is resolved by adding synchronization below.
So-called synchronization, multiple operations in the same time period can only have one in progress, a thread after running, will not
1) Synchronizing code blocks for synchronization
The Modified code:

 Public  class tickthread implements Runnable {    Private intTick =5;@Override     Public void Run() {//TODO auto-generated method stub        //synchronized declaring synchronous code blocks        synchronized( This) { for(inti =0; I <5; i++) {if( This.tick>0){Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"Run"+tick--); }            }        }    }}

You can also write the code that you want to synchronize into a method
The Modified code:

 Public  class tickthread implements Runnable {    Private intTick =5;@Override     Public void Run() {//TODO auto-generated method stub        //synchronized declaring synchronous code blocksFun (); } Public synchronized void  Fun(){ for(inti =0; I <5; i++) {if( This.tick>0){Try{Thread.Sleep ( -); }Catch(Interruptedexception e) {//TODO auto-generated catch blockE.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () +"Run"+tick--); }        }    }}
Deadlock problem

Multiple threads need to synchronize when sharing one data, but too much synchronization can generate deadlocks;

Java Basics Multi-Threading (2)

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.