Java based learning (eight) - multithreaded

Understanding thread

Process is an application running in a memory, the system is running a program that is created from a process run, the end of the process.

A thread is a unit execution process, the current process is responsible for program execution, a process in which at least one thread.

Multithreading is characterized by concurrent execution (the same period of time to perform multiple tasks), it does not actually increase the running speed, but can improve operational efficiency, allowing higher cpu usage.

About thread scheduling, divided into time-sharing scheduling and preemptive scheduling.

  • Preemptive scheduling mode, set the thread of high priority, priority thread priority use cpu.
  • Time-sharing scheduling, all the threads take turns using the cpu, the average allocation of time each thread occupy the cpu.

Multithreading is achieved 1.Java

Java multi-threading implemented in two ways:

  1. Inherit the Thread class and override the run method, to create a Thread object to execute.
  2. Runable defined interface implementation class and the run method override interface (thread of execution). Runnable class comprising implementing the run () method as the only thread of execution, and the Thread object passed to execution.

Implement Runnable than the Thread class inherits the advantages:

  1.  Multiple threads for the same program code to share the same resources.
  2. To avoid the limitations of single inheritance in java.
  3.  Increase the robustness of the program, decoupling operation, code can be shared by multiple threads, and thread independent codes.
  4.  Thread pool can only achieve Runable or Callable classes into a thread, not directly into the inheritance Thread class.

Construction method:

  • public Thread (): Allocates a new Thread object.
  • public Thread (String name): assign a new thread object a specified name.
  • public Thread (Runnable target): Allocates a new Thread object with the specified target.
  • public Thread (Runnable target, String name): assign a new thread object with the specified objectives and specify the name.

Common methods:

  • public String getName (): Get the current thread name.
  • public void start (): causes this thread to begin execution; Java Virtual Machine calls the run method of this thread.
  • public void run (): This thread mission to execute code defined here.
  • public static void sleep (long millis): the thread is currently executing a specified number of milliseconds to pause (temporarily stop the execution).
  • public static Thread currentThread (): Returns a reference to the currently executing thread object is.

The following code to understand the implementation process by:

// inherit Thead achieve 
class MyThead the extends the Thread {
     public MyThead (String name) {
         Super (name); 
    } 
    @Override 
    public  void RUN () { 
        System.out.println ( "I am the thread" + getName ()); 
    } 
} 


public  class TestThread {
     public  static  void main (String [] args) {
         // Create a thread object 
        MyThead MT = new new MyThead ( "M" );
         // open a new thread 
        mt.start (); 
        System.out.println ("I am the main thread" ); 
    } 
}
// achieve Runnable, override the run method of 
class MyRunable the implements Runnable { 
    @Override 
    public  void run () { 
        System.out.println ( "I am the thread" + Thread.currentThread () getName ().); 
    } 
} 
Public  class TestRunable {
     public  static  void main (String [] args) {
         // create objects MyRunable 
        MyRunable of Mr = new new MyRunable ();
         // Create a thread object 
        the thread T = new new the thread (of Mr, "T" );
         // thread running
         t.start ();
        System.out.println ( "I am the main thread" ); 
    } 
}

2. Thread Synchronization

When using multiple threads access the same resources, and modify resources in the thread, thread-safety issues will arise.

// achieve Runnable, override the run method of 
class MyRunable the implements the Runnable {
     Private  int A = 10 ; 
    @Override 
    public  void run () {
         the while (A> 0 ) { 
            
            the try { 
                the Thread.sleep ( 10 ); 
            } the catch (InterruptedException E) { 
                e.printStackTrace (); 
            } 
            a - =. 1 ; 
            System.out.println ( . "thread" + Thread.currentThread () getName () + " operation of a, a value of" + a); 
        } 

    } 
}
public  class TestRunable {
     public  static  void main (String [] args) {
         // create objects MyRunable 
        MyRunable of Mr = new new MyRunable ();
         // Create a thread object 
        the Thread = T1 new new the Thread (of Mr, "T1" ); 
        the Thread T2 = new new the thread (of Mr, "T2" ); 
        the thread T3 = new new the thread (of Mr, "T3" );
         // thread running 
        t1.start (); 
        t2.start (); 
        t3.start (); 

    } 
}

Since a plurality of threads operating variables a, resulting in an abnormal value a (-1 should not occur).

Thread safety problems are caused by multiple threads to modify global variables caused by the operation, then you need to use thread synchronization.

Thread Synchronization Principle:

When a thread operating resources, other thread is not allowed to operate, ensure the synchronization of data.

Java provides three ways to implement thread synchronization.

  • Synchronization code block: synchronized keyword can be used in the process of a block, block add exclusive access to the code.
  • Synchronization method: using synchronized modification methods. A thread in the implementation of this method, other threads are blocked.

  • Lock lock: also known as synchronization lock, lock and release the lock of the method.

Sync block:

//实现Runnable,重写run方法
class MyRunable implements Runnable{
    private int a = 10;
    //同步锁
    Object lock = new Object();
    @Override
    public void run(){
        while (true){
            synchronized (lock){
                if (a > 0){
                    try{
                        Thread.sleep(50);
                    }catch (InterruptedException e){
                        e.printStackTrace (); 
                    } 
                    A - =. 1 ; 
                    System.out.println ( . "Thread" + Thread.currentThread () getName () + " operation of a, a value of" + A); 

                } 

            } 
        } 
    } 
} 
public  class TestRunable {
     public  static  void main (String [] args) {
         // create objects MyRunable 
        MyRunable of Mr = new new MyRunable ();
         // Create a thread object 
        the thread = T1 new new the thread (of Mr, "T1" ); 
        the thread T2 = new new the thread (of Mr, "T2"); 
        The Thread T3 = new new the Thread (of Mr, "T3" );
         // thread running 
        t1.start (); 
        t2.start (); 
        t3.start (); 

    } 
}

Synchronization method:

//实现Runnable,重写run方法
class MyRunable implements Runnable{
    private int a = 10;
    @Override
    public void run(){
        while (true) {
            method1();
        }
    }
    //同步方法
    public synchronized void method1(){
        if (a > 0){
            try{
                Thread.sleep(50);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            a -= 1;
            System.out.println("线程"+Thread.currentThread().getName()+"操作了a,a的值为"+a);

        }
    }
}
public class TestRunable {
    public static void main(String[] args){
        //创建 MyRunable对象
        MyRunable mr = new MyRunable();
        //创建线程对象
        Thread t1 = new Thread(mr,"t1");
        Thread t2 = new Thread(mr,"t2");
        Thread t3 = new Thread(mr,"t3");
        //运行线程
        t1.start();
        t2.start();
        t3.start();

    }
}

Lock锁包含两个方法:

  • public void lock() :加同步锁。
  • public void unlock() :释放同步锁。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//实现Runnable,重写run方法
class MyRunable implements Runnable{
    private int a = 10;
    //同步锁
    Lock lock = new ReentrantLock();
    @Override
    public void run(){
        while (true){
            //加锁
            lock.lock();
            if (a > 0){
                try{
                    Thread.sleep(20);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                a -= 1;
                System.out.println("线程"+Thread.currentThread().getName()+"操作了a,a的值为"+a);

            }
            //释放锁
            lock.unlock();
        }
    }
}
public class TestRunable {
    public static void main(String[] args){
        //创建 MyRunable对象
        MyRunable mr = new MyRunable();
        //创建线程对象
        Thread t1 = new Thread(mr,"t1");
        Thread t2 = new Thread(mr,"t2");
        Thread t3 = new Thread(mr,"t3");
        //运行线程
        t1.start();
        t2.start();
        t3.start();

    }
}

3.线程状态

  • NEW:线程创建未启动。
  • Runnable:可运行。
  • Blocked:锁阻塞。当一个线程获得同步锁时,其他线程会被阻塞,直到获得同步锁。
  • Waiting:无限等待。当一个线程进入Waiting状态后,会无限等待,直到其他线程调用notify或者notifyAll方法唤醒(线程通信)。
  • TimedWaiting:计时等待当一个线程调用sleep方法时,程序会进入计时等待,直到时间结束。
  • Teminated:被终止。run方法未正常退出而死亡。

温馨提示

  • 如果您对本文有疑问,请在评论部分留言,我会在最短时间回复。
  • 如果本文帮助了您,也请评论关注,作为对我的一份鼓励。
  • 如果您感觉我写的有问题,也请批评指正,我会尽量修改。

 

Guess you like

Origin www.cnblogs.com/lyxdw/p/11668744.html