Java Multithreading and Contract starter sample _java

Source: Internet
Author: User
Tags cas mutex object object sleep static class thread class volatile

First, Java multithreading Basic introduction
Java multithreaded programming is also more important, in the actual business development often encounter this problem. Java multithreading, there are two ways to create threads in a traditional way. 1, inherit from thread class, overwrite Run method. 2, realize the Runnable interface, realize the Run method. The way to start a thread is to call the Start method, which is the run method that actually executes the call.
The reference code is as follows:

Copy Code code as follows:



Package com.jack.thread;

/**
* Thread Simple Demo Example program
*
* @author Pinefantasy
* @since 2013-10-31
*/
public class ThreadDemo1 {

/**
* The first way: Inherit from the thread class, overwrite the Run method
*/
public static class Test1thread extends Thread {

@Override
public void Run () {
for (int i = 0; i < i++) {
System.out.println ("Test1," + thread.currentthread (). GetName () + ", i =" + i);
}
}
}

/**
* The second way: Implement the Runnable interface, implementation of the Run method
*/
public static class Test2thread implements Runnable {

@Override
public void Run () {
for (int i = 0; i < i++) {
System.out.println ("Test2," + thread.currentthread (). GetName () + ", i =" + i);
}
}

}

   /**
     * <pre>
     *
      * Main thread is main threads
     * Branch line is: 1 2 33 Simple implementations
     *
 & nbsp;   * @param args
     */
    public static void Main (string[) args) {
        new Test1thread (). Start ()//boot thread 1
         new Thread (new Test2thread ()). Start ()//boot thread 2
         New Thread (new Runnable () {

@Override
public void Run () {
for (int i = 0; i < i++) {
System.out.println ("Test3," + thread.currentthread (). GetName () + ", i =" + i);
}
}
}). Start ();//Boot thread 3
}

}

Second, Java and the introduction of a simple contract
Multiple threads, uniformly handling the same variable demo code:

Copy Code code as follows:



Package com.jack.thread;

Import Java.util.concurrent.atomic.AtomicInteger;

/**
* Multithreading of the same variable to operate
*
* @author Pinefantasy
* @since 2013-10-31
*/
public class ThreadDemo2 {

private static int count = 0;

public static class Countthread implements Runnable {//1. This is a thread-safe issue. Shared variables messed up.

@Override


public void Run () {


for (int i = 0; i &lt; i++) {


try {


Thread.Sleep (50);


catch (Interruptedexception e) {


E.printstacktrace ();


}


count++;


System.out.println (Thread.CurrentThread (). GetName () + ", Count =" + count);


}


}

}

Private static Final Object lock = new Object ()//Lock object used here

public static class Count2thread implements Runnable {//This is a mutex method used

@Override
public void Run () {
Synchronized (lock) {//Mutex handling
for (int i = 0; i < i++) {
count++;
System.out.println (Thread.CurrentThread (). GetName () + ", Count =" + count);
}
}
}

}

private static Atomicinteger ai = new Atomicinteger ()//This side uses the Atomicxxx class of the concurrency package, using the CAs method: compare and Swap

public static class Count3thread implements Runnable {//Atomicinteger internal CAS implementation, using: Loop, judge, set trilogy Way

@Override
public void Run () {
for (int i = 0; i < i++) {
int tmp = Ai.incrementandget ();//Processing by CAS
System.out.println (Thread.CurrentThread (). GetName () + ", Count =" + tmp);
}
}

}

private static volatile int COUNTV = 0;//defined as volatile, allowing multithreading to perceive because values are placed in main memory

The public static class Count4thread implements Runnable {//volatile-defined variable is only said to be in main memory, at that time the + + operation is not atomic operation, this should be careful

@Override


public void Run () {


for (int i = 0; i &lt; i++) {


try {


Thread.Sleep (50)//Here Let the thread sleep, increase the probability of error


catch (Interruptedexception e) {


E.printstacktrace ();


}


countv++;//volatile to be used correctly, not to say that it is safe to define volatile, or to be aware of + +--operations are not atomic operations


System.out.println (Thread.CurrentThread (). GetName () + ", Count =" + Countv);


}


}

}

/**


* Simply write a test method using generics


*


* @param &lt;T&gt;


* @param t


* @throws instantiationexception


* @throws illegalaccessexception


* @throws interruptedexception


*/


public static &lt;T&gt; void Testtemplate (T-T) throws Instantiationexception, Illegalaccessexception, interruptedexception {


for (int i = 0; i &lt; 5; i++) {


if (t instanceof Runnable) {


class&lt;?&gt; C = T.getclass ();


Object object = C.newinstance ();


New Thread ((Runnable) object). Start ();


}


}


}

/**


* &lt;pre&gt;


* 1.test1 Thread Unsafe Demo example, the count variable does not get the expected effect


* 2.test2 is improved on the basis of test1, with mutual exclusion lock sync processing


* 3.test3 is improved on test1 basis and Atomicinteger class is used to implement


* 4.test4 the problematic method, because i++ is not atomic, define count as volatile type


*


* @param args


* @throws interruptedexception


* @throws illegalaccessexception


* @throws instantiationexception


*/


public static void Main (string[] args) throws Interruptedexception, Instantiationexception, illegalaccessexception {


1. Test 1


Testtemplate (New Countthread ());


2. Test 2


Testtemplate (New Count2thread ());


3. Test 3


Testtemplate (New Count3thread ());


4. Test 4


Testtemplate (New Count4thread ());


Thread.Sleep (15000);


System.out.println (count);


System.out.println (Ai.get ());


System.out.println (COUNTV);


}

}

Producer-Consumer model
Producer (the thread that generates the product)--responsible for generating the product consumer (the thread of the consumer product)--"responsible for consumer products"
Car buyers, consumers. The person who sells cars, sells cars, and treats them as producers. Warehouses, places where cars are kept. Car factories, where real cars are built.
The reference code is as follows:
The code with no synchronization mechanism is as follows:

Copy Code code as follows:



Package com.jack.thread;

Import java.util.ArrayList;
Import java.util.List;
Import Com.jack.thread.ThreadDemo3.CarBigHouse.Car;

/**
* The first version of the producer and consumer threads
*
* @author Pinefantasy
* @since 2013-11-1
*/
public class ThreadDemo3 {

/**
* Sell the car as a producer thread
*/
public static class Carseller implements Runnable {

Private Carbighouse Bighouse;

Public Carseller (Carbighouse bighouse) {
This.bighouse = Bighouse;
}

@Override
public void Run () {
for (int i = 0; i < i++) {//As producer thread, adding a car to the warehouse is actually triggering an increase in the car
int count = Bighouse.put ();
System.out.println ("Production car-->count =" + count);
}
}

}

/**
* The person who buys the car as a consumer thread
*/
public static class Consumer implements Runnable {

Private Carbighouse Bighouse;

Public Consumer (Carbighouse bighouse) {
This.bighouse = Bighouse;
}

@Override
public void Run () {
for (int i = 0; i < i++) {//As a consumer thread, extracting a car from a warehouse is actually triggered, extracting a car from the warehouse.
int count = Bighouse.get ();
System.out.println ("Consumer Car-->count =" + count);
}
}

}

/**
* This is the car, Big house, the warehouse room for the car.
*/
public static class Carbighouse {

public int carnums = 0;//This is the total number of cars in the warehouse house.
Public List<car> Carlist = new arraylist<car> ()//This simulates the List used to put the car.

public int put () {//provide the manufacturer with an interface for car to warehouse
Car car = Carfactory.makenewcar ();
Carlist.add (CAR)//Add to Warehouse
Total number of carnums++;//increased by 1
return carnums;
}

public int Get () {//provide consumer access to car interface from this side
Car car = null;
if (carlist.size ()!= 0) {//size is not empty to pick up the car
Car = Carlist.get (Carlist.size ()-1);//Fetch last car
Carlist.remove (car);//Remove from library list
carnums--;//total reduced by 1
}
return carnums;
}

public static class Car {

Public String carname;//Car name
Public double carprice;//Car price

Public car () {
}

Public car (String Carname, double carprice) {
This.carname = Carname;
This.carprice = Carprice;
}
}
}

/**
* Use static factory to create car objects, this is a simple simulation, do not do the design pattern of too much elegant
*/
public static class Carfactory {

Private Carfactory () {
}

public static car Makenewcar (String carname, double carprice) {
Return to New car (Carname, carprice);
}

public static Car Makenewcar () {
Return to new car ();
}
}

/**
* The first version of the producer and consumer threads, without adding a synchronization mechanism to the demo example
*
* @param args
*/
public static void Main (string[] args) {
Carbighouse bighouse = new Carbighouse ();
New Thread (New Carseller (Bighouse)). Start ();
New Thread (New Consumer (Bighouse)). Start ();
}

}

The code to add the mutex is as follows:

Copy Code code as follows:



Package com.jack.thread;

Import java.util.ArrayList;
Import java.util.List;
Import Com.jack.thread.ThreadDemo4.CarBigHouse.Car;

/**
* Second version of producer consumer Thread
*
* @author Pinefantasy
* @since 2013-11-1
*/
public class ThreadDemo4 {

/**
* Sell the car as a producer thread
*/
public static class Carseller implements Runnable {

Private Carbighouse Bighouse;

Public Carseller (Carbighouse bighouse) {
This.bighouse = Bighouse;
}

@Override
public void Run () {
for (int i = 0; i < i++) {//As producer thread, adding a car to the warehouse is actually triggering an increase in the car
int count = Bighouse.put ();
System.out.println ("Production car-->count =" + count);
}
}

}

/**
* The person who buys the car as a consumer thread
*/
public static class Consumer implements Runnable {

Private Carbighouse Bighouse;

Public Consumer (Carbighouse bighouse) {
This.bighouse = Bighouse;
}

@Override
public void Run () {
for (int i = 0; i < i++) {//As a consumer thread, extracting a car from a warehouse is actually triggered, extracting a car from the warehouse.
int count = Bighouse.get ();
System.out.println ("Consumer Car-->count =" + count);
}
}

}

/**
* This is the car, Big house, the warehouse room for the car.
*/
public static class Carbighouse {

public int carnums = 0;//This is the total number of cars in the warehouse house.
Public List<car> Carlist = new arraylist<car> ()//This simulates the List used to put the car.

Directly add on synchronized keyword way, member method, lock is current Bighouse object
This lock is a mutex, and at the same time, only one thread can access the code inside.

        public synchronized int put () {//provide the manufacturer with a car to the warehouse interface
             Car car = Carfactory.makenewcar ();
            carlist.add (CAR)//Add to warehouse
             carnums++;//Total added 1
             return carnums;
       }

public synchronized int Get () {//provide consumer access to car interface from this side
Car car = null;
if (carlist.size ()!= 0) {//size is not empty to pick up the car
Car = Carlist.get (Carlist.size ()-1);//Fetch last car
Carlist.remove (car);//Remove from library list
carnums--;//total reduced by 1
}
return carnums;
}

public static class Car {

Public String carname;//Car name
Public double carprice;//Car price

Public car () {
}

Public car (String Carname, double carprice) {
This.carname = Carname;
This.carprice = Carprice;
}
}
}

/**
* Use static factory to create car objects, this is a simple simulation, do not do the design pattern of too much elegant
*/
public static class Carfactory {

Private Carfactory () {
}

public static car Makenewcar (String carname, double carprice) {
Return to New car (Carname, carprice);
}

public static Car Makenewcar () {
Return to new car ();
}
}

/**
* The second version of the producer and consumer threads, plus the method of synchronizing the mechanism
*
* @param args
*/
public static void Main (string[] args) {
Carbighouse bighouse = new Carbighouse ();
New Thread (New Carseller (Bighouse)). Start ();
New Thread (New Consumer (Bighouse)). Start ();
}

}

/Use the object class wait and notify method or Notifyall method (Note Notify method and Notifyall method difference)//notify is to wake one of the waiting threads. Notifyall is to wake up all the other threads that are waiting, but it depends on which thread can get to the lock or the competition.
Thread state: Create, run, block, destroy state. (more congestion, such as waiting for data io input, blocking.) )

Copy Code code as follows:



Package com.jack.thread;

Import java.util.ArrayList;
Import java.util.List;
Import Com.jack.thread.ThreadDemo4.CarBigHouse.Car;

/**
* Second version of producer consumer Thread
*
* @author Pinefantasy
* @since 2013-11-1
*/
public class ThreadDemo4 {

/**
* Sell the car as a producer thread
*/
public static class Carseller implements Runnable {

Private Carbighouse Bighouse;

Public Carseller (Carbighouse bighouse) {
This.bighouse = Bighouse;
}

@Override
public void Run () {
for (int i = 0; i < i++) {//As producer thread, adding a car to the warehouse is actually triggering an increase in the car
int count = Bighouse.put ();
System.out.println ("Production car-->count =" + count);
}
}

}

/**
* The person who buys the car as a consumer thread
*/
public static class Consumer implements Runnable {

Private Carbighouse Bighouse;

Public Consumer (Carbighouse bighouse) {
This.bighouse = Bighouse;
}

@Override
public void Run () {
for (int i = 0; i < i++) {//As a consumer thread, extracting a car from a warehouse is actually triggered, extracting a car from the warehouse.
int count = Bighouse.get ();
System.out.println ("Consumer Car-->count =" + count);
}
}

}

/**
* This is the car, Big house, the warehouse room for the car.
*/
public static class Carbighouse {

public int carnums = 0;//This is the total number of cars in the warehouse house.
Public List<car> Carlist = new arraylist<car> ()//This simulates the List used to put the car.
public static final int max = 100;//simple setting, do the upper limit set

Private Object lock = new Object ()//wait and notify with Object to handle synchronization problems

public int put () {//provide the manufacturer with an interface for car to warehouse


Synchronized (lock) {


if (carlist.size () = max) {//up to the upper limit, no more car will be produced


try {


Lock.wait ()//for blocking processing


catch (Interruptedexception e) {


E.printstacktrace ();


}


}


Car car = Carfactory.makenewcar ();


Carlist.add (CAR)//Add to Warehouse


Total number of carnums++;//increased by 1


Lock.notify ()//Wake up waiting thread


return carnums;


}


}

public int Get () {//provide consumer access to car interface from this side


Car car = null;


Synchronized (lock) {


if (carlist.size () = = 0) {//No car can be used for consumption


try {


Lock.wait ();


catch (Interruptedexception e) {


E.printstacktrace ();


}


}


if (carlist.size ()!= 0) {//size is not empty to pick up the car


Car = Carlist.get (Carlist.size ()-1);//Fetch last car


Carlist.remove (car);//Remove from library list


carnums--;//total reduced by 1


}


Lock.notify ();


return carnums;


}


}

public static class Car {

Public String carname;//Car name
Public double carprice;//Car price

Public car () {
}

Public car (String Carname, double carprice) {
This.carname = Carname;
This.carprice = Carprice;
}
}
}

/**
* Use static factory to create car objects, this is a simple simulation, do not do the design pattern of too much elegant
*/
public static class Carfactory {

Private Carfactory () {
}

public static car Makenewcar (String carname, double carprice) {
Return to New car (Carname, carprice);
}

public static Car Makenewcar () {
Return to new car ();
}
}

/**
* The second version of the producer and consumer threads, plus the method of synchronizing the mechanism
*
* @param args
*/
public static void Main (string[] args) {
Carbighouse bighouse = new Carbighouse ();
New Thread (New Carseller (Bighouse)). Start ();
New Thread (New Consumer (Bighouse)). Start ();
}

}

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.