Java Fundamentals 10 (multithreading 2)

Source: Internet
Author: User

    1. Common Methods of threading

Public final void Join () thread join

Action: waits for the thread to abort, other threads can continue to execute

public static void Yield (): Thread comity

Role: Pauses the currently executing thread object and executes other threads. Make the execution of the threads more harmonious, but not in fact.

Public final void Stop (): Thread death: Direct Kill

public void Interrupt (): Thread death: Direct Kill, before death, can also have a last words (will execute the following code, and then die).

static void sleep (long Millis) thread sleeps: The thread sleeps for a while and wakes himself up.

2. Thread Life cycle

A. New: Creating a Thread Object

B. Ready: After Start (), there is CPU execution, but no execution qualification

C. Run: There is CPU execution right, also has the CPU's execution qualification

D. may be blocked: Hibernate or wait

E. Death: The Run () method finishes executing, calling the Stop () or Interrup () method

The life cycle diagram is as follows:

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M00/96/CC/wKiom1klfCmwWlezAABkI2Q_sBg914.png "title=" Qq20170524202446.png "alt=" Wkiom1klfcmwwlezaabki2q_sbg914.png "/>

3. Inter-thread communication

Definition: Actions for the same resource between different threads


Student--Class of the resources being set

Setthread--Set thread

GetThread--Get thread

Studnetdemo--Test class


public class Student {

private String name;

private int age;

As a token of an object, False indicates that the object has no data

Private Boolean flag;

Provides public method settings information

Public synchronized void SetInfo (String name,int age) {

if (This.flag) {

Wait

try {

This.wait ();

} catch (Interruptedexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

}

If there is no value, set the data to the object here

THIS.name = name;

This.age = age;

Change tag, wake fetch thread fetch data

This.flag = true;

This.notify ();

}

Provide a public way to get information

Public synchronized void GetInfo () {

if (!this.flag) {

No value

try {

This.wait ();

} catch (Interruptedexception e) {

TODO auto-generated Catch block

E.printstacktrace ();

}

}

Have data, take data

System.out.println (this.name+ "--" +this.age);

After the data is taken, there is no data.

This.flag = false;

This.notify ();

}

}


public class GetThread implements runnable{

Private Student S;

Public GetThread (Student s) {

THIS.S = s;

}

@Override

public void Run () {

Get thread, get name and age of student object

while (true) {

S.getinfo ();

}

}

}

}



public class Setthread implements runnable{

Private Student S;

private int x=0;

Public Setthread (Student s) {

THIS.S = s;

}

@Override

public void Run () {

Set name and age for student objects

while (true) {

if (x%2==0) {

S.name = "Jay Chou";

S.age = 40;

}else {

S.name = "Lin Jia";

S.age = 30;

}

x + +;

}

}

}

public class Studentdemo {

public static void Main (string[] args) {

Create Student objects

Student s = new Student ();

Create set thread and get thread

Setthread st = new Setthread (s);

GetThread GT = new GetThread (s);

thread T1 = new Thread (ST);

Thread t2 = new Thread (GT);

Open Thread

T1.start ();

T2.start ();

}


}

4. Thread groups

Definition: Java uses Threadgroup to represent thread groups, which can classify a batch of threads, and Java allows programs to control thread groups directly. By default, all threads belong to the main thread group.

Main methods:

Public final Threadgroup Getthreadgroup (): Gets the thread group object corresponding to threads

Thread (threadgroup group, Runnable target): Threading Settings grouping


Case 1: Create a thread to get the corresponding thread group object and get the name

Create Two threads

MyThread MT1 = new MyThread ();

MyThread mt2 = new MyThread ();

Gets the thread group object corresponding to the above two threads

Threadgroup TG1 = Mt1.getthreadgroup ();

Threadgroup TG2 = Mt2.getthreadgroup ();

Gets the name of the thread Group object

System.out.println (Tg1.getname ());

System.out.println (Tg2.getname ());

Case 2: Creating a thread Group object, assigning thread groups to threads


Threadgroup TG = new Threadgroup ("big");

thread t3 = new Thread (TG, new myrunnable ());

thread T4 = new Thread (TG, new myrunnable ());

Get thread group objects for T3 and T4

Threadgroup TG3 = T3.getthreadgroup ();

Threadgroup TG4 = T4.getthreadgroup ();

System.out.println (Tg3.getname ());

System.out.println (Tg4.getname ());


5. Thread pool

Introduction Reason: The program starts a new thread cost is relatively high because it involves interacting with the operating system. Using a thread pool can improve performance, especially when you want to create a lot of short-lived threads in your program.

Features: line constructor after each thread code ends, it does not die, but returns to the thread pool again to become idle, waiting for the next object to be used.

How to create a thread pool:

public static Executorservice newfixedthreadpool (int nthreads)

Steps to use the thread pool:

A. Creating a thread pool object

Executorservice pool = Executors.newfixedthreadpool (2);


B. Creating an runnable instance

myrunnable my = new myrunnable ();


C. Submitting Runnable instances

Pool.submit (my);

Pool.submit (my);


D. Closing the thread pool

Pool.shutdown ();


6. Timers (timer):

Main methods:

Public Timer () constructs

public void Schedule (timertask task, long delay) how long delay to perform the task

public void Schedule (TimerTask task,long Delay,long period) Delays how long the task is performed and how often it is executed at a later time

public boolean cancel () cancels this task


TimerTask

public abstract void Run () puts the task code that you want to execute


Case: 5 seconds delay, print Hellojava, print once every second

public static void Main (string[] args) {

Timer T = new timer ();

T.schedule (New MyTimerTask2 (), 5000, 1000);

/**

* Parameter 1: The task to be performed

* Parameter 2: How long does the delay take?

* Parameter 3: After execution once, how often do you repeat

*/

}


}


Class MyTimerTask2 extends timertask{

@Override

public void Run () {

System.out.println ("Hellojava");

}

}


Java Foundation 10 (multithreaded 2)

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.