Talk about threading in Java (primary concept)

Source: Internet
Author: User

Defining definitions of processes and threads see this introduction
Http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html
Without fine-keying the definition
We can assume that a task in the operating system is a process like word,qq can be seen as a process.
On the other hand, if the function call inside the process is a line, then it's a single thread.
If there are multiple lines that is multithreaded and each of the processes executed within the process is called a thread


We define our own thread before we customize the thread, let's look at some Java classes about threading
There are two main
One is interface Runnable
There is only one way to run ()
One is class Thread.
In fact it also implements the Runnable interface (which must also be rewritten with the Run method), and it has a method called start


Let's look at the first example, by the way, the difference between start and run

public class TestThread1 {public static void main (String args[]) {Runner1 r = new Runner1 (); R.start ();        R.run (); for (int i=0; i<100; i++) {System.out.println ("Main Thread:------" + i);}}} Class Runner1 extends Thread {public void run () {for (int i=0; i<100; i++) {System.out.println ("Runner1:" + i);}}}
The result of the run is Main Thread: With Runner1 ... Alternating output

That's when you run two threads, one main thread, one R thread.
If you change the R.start to R.run then it is 100 Runner1 first. Then there's 100 main Thread
Why?
Let's take a closer look if we call R.run () that's not the function call!!!
So one word our custom thread must implement the Run method but call it with start ()!


And look at another way to define threads

public class TestThread1 {public static void main (String args[]) {Runner1 r = new Runner1 (); Thread t = new Thread (r), T.start (), for (int i=0; i<50; i++) {System.out.println ("Main Thread:------" + i);}}} Class Runner1 implements Runnable {public void run () {for (int i=0; i<50; i++) {System.out.println ("Runner1:" + i);}}}


How do we choose between two ways to define threads?
Choose the second way to implement the Runable interface
Because once we inherit the thread class, we can no longer inherit another class.
So you can inherit the way the class can implement the interface.


Sleep Interrupt Stop Flag
public class Testthread3{public static void Main (String args[]) {Runner3 r = new Runner3 (); Thread t = new Thread (r); T.start ();}} Class Runner3 implements Runnable {public void run () {for (int i=0; i<30; i++) {if (i%10==0 && i!=0) {try{thread. Sleep (2000); }catch (interruptedexception e) {}}system.out.println ("No." + i);}}


Look at this example it runs the result is to print out 0-9 then stop two seconds and then print out 10-19 ...
Thread.Sleep () is the length of time it takes for a program to hibernate. Specified in milliseconds by parameter
But be aware that sleep throws interruptedexception exceptions.


public class Testinterrupt {public  static void Main (string[] args) {    MyThread thread = new MyThread ();    Thread.Start ();    try {thread.sleep (10000);}    catch (Interruptedexception e) {}    Thread.Interrupt ();}  } Class MyThread extends Thread {Boolean flag = true;  public void Run () {    while (true) {      System.out.println ("= = =" +new Date () + "= = =");      try {        sleep (n);      } catch (Interruptedexception e) {       return;      }    }  }


The result of this code is that every second output the current time and so on after 10 seconds of running and stop
We also see that sleep itself may be "disturbed" is interrupt we in the main line thread call Thread.Interrupt ();
equals throws an exception then thread can only execute the code return inside the catch.
In addition, thread has a method called Stop (obsolete) look at the name and we'll know what it can do.
But he's even more violent than interrupt. Interrupt, there's a catch. Stop is a chance to do anything else before it's over.


Of course, it's not hard to end this "dead loop" thread.
Mythread with a Boolean flag so that it is true while (true) is changed to while (flag)
When you want to end it, let Flag=false in the main function.


Join yield Priority
public class Testinterrupt {public  static void Main (string[] args) {    MyThread thread = new MyThread ();    Thread.Start ();    try {thread.sleep (10000);}    catch (Interruptedexception e) {}    Thread.Interrupt ();}  } Class MyThread extends Thread {Boolean flag = true;  public void Run () {    while (true) {      System.out.println ("= = =" +new Date () + "= = =");      try {        sleep (n);      } catch (Interruptedexception e) {       return;      }    }  }


By looking at the results of this code, we understand that join is the merging of threads
As above is waiting for TI's run to complete the main thread and then continue to go down a bit of the thread call as a function call feeling
Only the yield () method of thread is that the thread voluntarily discards the time slices he owns for other threads to use (of course, just give up the next time you have a movie and it won't give up)
The code is as follows


public class Testinterrupt {public  static void Main (string[] args) {    MyThread thread = new MyThread ();    Thread.Start ();    try {thread.sleep (10000);}    catch (Interruptedexception e) {}    Thread.Interrupt ();}  } Class MyThread extends Thread {Boolean flag = true;  public void Run () {    while (true) {      System.out.println ("= = =" +new Date () + "= = =");      try {        sleep (n);      } catch (Interruptedexception e) {       return;      }    }  }


The runtime will find that every time a thread prints its own name and a sequence number of 10, the next run is not its own yield () and it gives up the use of the Times slice.
There are two ways to prioritize (priority) SetPriority getpriority
Priority from 1 to 10 10 for highest
The higher the priority, the greater the chance of acquiring the time slice.
The code is as follows
public class Testpriority {public static void main (string[] args) {thread T1 = new Thread (new T1 ()); Thread t2 = new Thread (new T2 ()), t1.setpriority (thread.norm_priority + 3); T1.start (); T2.start ();}} Class T1 implements Runnable {public void run () {for (int i=0; i<1000; i++) System.out.println ("T1:" + i);}} Class T2 implements Runnable {public void run () {for (int i=0; i<1000; i++) System.out.println ("------T2:" + i);}}






Talk about threading in Java (primary concept)

Related Article

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.