Java multithreading notes (2) and java multithreading notes

Source: Internet
Author: User

Java multithreading notes (2) and java multithreading notes

The difficulty of java multithreading lies in the communication between multiple threads during synchronization and concurrent running. When processing thread synchronization, java commonly uses the following methods:

1. synchronized keyword.

2. Lock: the Lock is displayed.

3. Semaphore.

 

Thread synchronization problem introduction:

Create a bank Account class and add a dollar to the same Account class instance by creating and starting 100 threads. If the preceding three methods are not used:

Code:

Import java. util. concurrent. executorService; import java. util. concurrent. executors; public class AccountWithoutSync {private static Account account Account = new Account (); // instantiate an account public static void main (String [] args) {long start = System. currentTimeMillis (); // use ExecutorService to create the thread pool ExecutorService executor = Executors. newCachedThreadPool (); for (int I = 0; I <10010000i000000000000000000000000execuutor.exe cute (new AddPennyTask ();} // close the thread The pool returns the unfinished list executor even if there are still unfinished threads in the thread pool. shutdown (); // after shutdown, ensure that the unfinished threads continue to complete. If all the tasks in the thread pool are completed, isTerminated returns truewhile (! Executor. isTerminated () {} long end = System. currentTimeMillis (); // balance indicates System. out. println ("the current account balance is:" + account. getBalance (); System. out. println ("time spent in microseconds:" + (end-start) + "microsecond ");} // This thread only calls one method public static class AddPennyTask implements Runnable {@ Overridepublic void run () {account. deposit (1) ;}}// an internal class is used for Account-related processing. public static class Account {private int balance = 0; public int getBalance () {return balance ;} public void deposit (int amount) {int newBalance = balance + amount; // to make the error more explicit try {Thread. sleep (4); // 5 ms} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} balance = newBalance; // actually, It is balance + = amount; // The result of this code segment is around 100 and 99 }}}

 

Run public static class Account2 {private static Lock lock = new ReentrantLock (); private int balance = 0; public int getBalance () {return balance;} public void deposit (int amount) {lock. lock (); try {int newBalance = balance + amount; Thread. sleep (4); balance = newBalance;} catch (InterruptedException e) {e. printStackTrace ();} finally {lock. unlock ();}}}

 

Run: public static class Account

{Private static Semaphore semaphore = new Semaphore (1); // create a Semaphore private int balance = 0; public int getBalance () {return balance;} public void deposit (int amount) {try {semaphore. acquire (); int newBalance = balance + amount; Thread. sleep (4); balance = newBalance;} catch (InterruptedException e) {e. printStackTrace ();} finally {semaphore. release (); // returns a semaphore }}}

 

There are a lot of articles on java multithreading on the Internet, many of which are written in series, but I personally think that there is something interesting like multithreading, So I still have to calm down and taste it. The three methods above are as follows, it can solve the problem of multi-thread synchronization and will continue learning later. Well, come on.

This article is from the blog garden. For more information, see the source.


Write a multi-threaded program in JAVA, write four threads, two of which add 1 to a variable, the other two minus 1 to a variable, and output

What do we need to do to create a new thread? Obviously, we must specify the code to be executed by this thread, and this is all we need to do to implement multithreading in Java!

Amazing! How does Java achieve this? Passed class! As a fully object-oriented language, Java provides a class of java. lang. thread to facilitate multi-threaded programming. This class provides a large number of methods to facilitate our control of various threads. We will discuss this class in the future.

So how can we provide the code to be executed by threads for Java? Let's take a look at the Thread class. The most important method of the Thread class is run (), which is called by the Thread class method start () and provides the code to be executed by our Thread. To specify our own code, we only need to overwrite it!

Method 1: Inherit the Thread class and overwrite the run () method. In the subclass of the created Thread class, rewrite run () and add the code to be executed by the Thread. The following is an example:

Public class MyThread extends Thread {

Int count = 1, number;

Public MyThread (int num ){

Number = num;

System. out. println ("creation thread" + number );

}

Public void run (){

While (true ){

System. out. println ("Thread" + number + ": count" + count );

If (++ count = 6) return;

}

}

Public static void main (String args []) {

For (int I = 0; I <5; I ++) new MyThread (I + 1). start ();

}

}

Write a multi-threaded program in JAVA, for example, write four threads, two to one variable minus one, and output

Public class ThreadTest1 {
Private int j;
Public static void main (String args []) {
ThreadTest1 tt = new ThreadTest1 ();
Inc inc = tt. new Inc ();
Dec dec = tt. new Dec ();
For (int I = 0; I <2; I ++ ){
Thread t = new Thread (inc );
T. start ();
T = new Thread (dec );
T. start ();
}
}
Private synchronized void inc (){
J ++;
System. out. println (Thread. currentThread (). getName () + "-inc:" + j );
}
Private synchronized void dec (){
J --;
System. out. println (Thread. currentThread (). getName () + "-dec:" + j );
}
Class Inc implements Runnable {
Public void run (){
For (int I = 0; I <100; I ++ ){
Inc ();
}
}
}
Class Dec implements Runnable {
Public void run (){
For (int I = 0; I <100; I ++ ){
Dec ();
}
}
}
}
 

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.