Java Multithreading Technology Core

Source: Internet
Author: User
Tags thread class

1. three main features of the process:

Independence: With its own independent address space, a process cannot directly access the address space of other processes.

Dynamic: is a collection of instructions that are active in a system.

Concurrency: A single process can be performed concurrently on multiple processors, with no impact on each other.

2. Differences in concurrency and parallelism:

Parallel is the same time, there are multiple instructions on multiple processors at the same time, concurrency is, fast rotation execution, in fact, on the macro, multiple processes at the same time.

3. Threading Features:

A thread must have a parent process that belongs to itself, a thread can have its own stack, a program counter, a local variable, a thread can share all the resources in the parent process with other threads, the thread does not know if there are other threads present, and the thread is preempted.

4. Multithreaded Programming:

shared resources; The cost of allocating resources for creating threads is small;Java built-in multithreading support.

5. Thread creation:

Method One: Inherit the thread class creation process

public class Firstthread extends Thread

{

Private int i;

public void Run () {

Sop (GetName ());

}

public static void Main (string[] args) {

Create the first thread

New Firstthread (). Start ();

Create a second thread

New Firstthread (). Start ();

}

}

Features: Multiple threads cannot share instance variables.

Method Two: Implement the Runnable interface to create the thread class

public class Firstthread extends Thread

{

Private int i;

public void Run () {

Sop (Thread.currentThread.getName ());

}

public static void Main (string[] args) {

Create the first thread

Firstthread ft = new Firstthread ();

New Thread (ST, "thread 1"). Start ();

}

}

Feature: You can share instance variables of a thread class

Cause: The program creates only the target of the thread , and multiple threads can share a target, so you can share an instance variable of a thread class.

6. The life cycle of a thread:

New and ready:

1) New thread is created, in new state,theJVM categorizes the memory for it, initializes the value of the member variable.

2) Start thread with the start method, you cannot call the run method directly, otherwise the run method is treated as a generic method.

Running and blocking state, thread dead.

7. Control thread: Thejoin method, when called, the thread will be blocked until the thread that called the join method finishes executing before it can continue execution.

8. Background thread: Daemon thread, Sprite thread , If all the front-end threads are dead, they will die automatically.

The Setdaemon () method of the thread object to go to the display settings. , but must be set before the Start method executes.

9. Thread Sleep: Sleeping(), during the sleep period, the thread does not get an opportunity to execute, even if there are no other processes that can be executed, The thread in sleep will not execute.

Thread.Sleep (1000);

Sleep 1000ms

10. Thread Concession: Let the currently executing thread pause, but do not block the thread, just transfer it to the ready state, let the system's thread scheduler to reschedule. When a method performs a concession, only the thread with the same priority or priority higher than his is given the opportunity to execute.

11. Thread Synchronization Issues:

Directory structure:

Example Analysis:

Package Tongbu;

Public class Account {

Declare the account number

Private String Accountno;

Public String Getaccountno () {

return Accountno;

}

Public void Setaccountno (String accountno) {

this. Accountno = Accountno;

}

Declare the money

Private double balance;

Public double GetBalance () {

return balance;

}

Public void setbalance (double balance) {

this. Balance = balance;

}

constructor of the Accountno and balance

Public Account (String Accountno, double balance) {

Super ();

this. Accountno = Accountno;

this. Balance = balance;

}

Overriding the Hashcode method and Equals method to do sure it is a same user

Public int hashcode () {

return Accountno.hashcode ();

}

Public boolean equals (Object obj) {

if (this ==obj) {

return true;

}

if (obj!=null&&obj.getclass () ==account. class) {

Tranverse the obj to a target

Account target = (account) obj;

if (Target.getaccountno () ==accountno) {

return true;

}Else{

return false;

}

}

return false;

}

}

Package Tongbu;

Public class Drawthread extends thread{

User ' s account ID

Private Account Account;

The money number of the user want to draw

Private double Drawamount;

Contructor of Drawthread

Public Drawthread (String name,account account,double drawamount) {

Super (name);

this. Account=account;

this. Drawamount=drawamount;

}

The thread main run function

Public void Run () {

synchronized (account) {

Check the remain money is enough

If the original money can be sufficient

if (Account.getbalance () >=drawamount) {

System. out. println ("Draw money successfullly!:" +drawamount);

Update the remain Money

Account.setbalance (Account.getbalance ()-drawamount);

Output the remain Money

System. out. println ("Remain money is:" +account.getbalance ());

}Else{

System. out. println ("Draw money failed!");

}

}

}

}

Package Tongbu;

Public class drawtest {

Public Static void Main (string[] args) {

Instance a Account object

Account Acct = new account ("10001", 10000);

Let both thread to draw money from the same account

New Drawthread ("shareing", acct,8000). Start ();

New Drawthread ("MM", acct,8000). Start ();

}

}

Method one: With synchronized (obj) {

}

Method Two: Synchronous Lock:

Class x{

PRIAVTE Final Reentrantlock lock = new Reentrantlock ();

public void M () {

Jiasuo

Lock.lock ();

try{

//////

}

finally{

Jiesuo

Lock.unlock ();

}

}

}

12. Thread Communication:

1) Traditional method:Wait () notify () Notifyall ( )

2) use condition Control

Package tongxin;

Import java.util.concurrent.locks.Condition;

Import Java.util.concurrent.locks.Lock;

Import Java.util.concurrent.locks.ReentrantLock;

public class Account {

Define a Lock Object

Private Final lock lock = new Reentrantlock ();

Get the condition of object

Private final Condition cond = Lock.newcondition ();

Mark to check there are remain money

Private Boolean flag=false;

Declare the Account ID

Private String Accountno;

Public String Getaccountno () {

return accountno;

}

public void Setaccountno (String accountno) {

This.accountno = Accountno;

}

Declare the money

private double balance;

Public double getbalance () {

return balance;

}

public void setbalance (double balance) {

This.balance = balance;

}

constructor of the Accountno and balance

Public account (String Accountno, double balance) {

Super ();

This.accountno = Accountno;

This.balance = balance;

}

Overriding the Hashcode method and Equals method to do sure it is a same user

public int hashcode () {

return Accountno.hashcode ();

}

public boolean equals (Object obj) {

if (this==obj) {

return true;

}

if (Obj!=null&&obj.getclass () ==account.class) {

Tranverse the obj to a target

Account target = (account) obj;

if (Target.getaccountno () ==accountno) {

return true;

}else{

return false;

}

}

return false;

}

The Mehod to draw money

public void Draw (double drawamount) {

Lock.lock ();

try{

No body has deposied money to the account

if (!flag) {

Cond.await ();

}else{

Execute the draw Money opreration

System.out.println ("Draw money:" +drawamount);

Balance-=drawamount;

System.out.println ("Remain money:" +balance);

Set the flag false means money used up

Flag=false;

Notify all thread to Deposite

Cond.signalall ();

}

}catch (Interruptedexception ex) {

Ex.printstacktrace ();

}

finally{

Lock.unlock ();

}

}

The Mehod to deposit money

public void deposit (double depositamount) {

Lock.lock ();

try{

No body has deposied money to the account

if (flag) {

Cond.await ();

}else{

Execute the draw Money opreration

System.out.println ("Deposit money:" +depositamount);

}

Balance+=depositamount;

System.out.println ("Remain money:" +balance);

Set the flag false means money used up

Flag=true;

Notify all thread to Deposite

Cond.signalall ();

}catch (Interruptedexception ex) {

Ex.printstacktrace ();

}

finally{

Lock.unlock ();

}

}

}

Package Tongxin;

Public class Depositthread extends thread{

Private Account Account;

Private double Drawamount;

Public Depositthread (String name,account account,double drawamount) {

Super (name);

this. Account=account;

this. Drawamount=drawamount;

}

Public void Run () {

for (int i=0;i<5;i++) {

Account.deposit (Drawamount);

}

}

}

Package Tongxin;

Public class Drawthread extends Thread {

Private Account Account;

Private double Drawamount;

Public Drawthread (String name,account account,double drawamount) {

Super (name);

this. Account=account;

this. Drawamount=drawamount;

}

Public void Run () {

for (int i=0;i<5;i++) {

Account.draw (Drawamount);

}

}

}

Package Tongxin;

Public class tongxintest {

Public Static void Main (string[] args) {

Account Acct = new account ("10101", 0);

New Drawthread ("Draw Money", acct,800). Start ();

New Depositthread ("Deposit money", acct,800). Start ();

}

}

3) control using a blocking queue

Java Multithreading Technology Core

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.