Java beginner - Multithreading

A difference, process and thread

    Process refers to the application instance of the program, it will occupy a separate memory space and system resources

    Thread refers to the basic unit of CPU scheduling and dispatching, unified program to perform multiple operations, called threads

  1. What is multi-threaded

    If you run multiple threads in a process at the same time, to do different things, it is called "multi-threaded" multiple threads alternately CPU resources, rather than a true parallel execution

  2. Multi-threaded benefits

    Make full use of CPU resources to simplify the programming model to bring a good user experience

  3. The main thread

    main () method spawns a thread inlet i.e. the main thread of the other sub-thread must be the last complete execution because it performs various closing action

Second, the way to create multi-threaded

  Method One: Thread class inherits write simple, direct operation of the thread is suitable for single inheritance

Package dome2; 

public  class the MyThread the extends the Thread {
     // Create custom thread run method override 
    public  void run () {
         for ( int I = 0; I <10; I ++ ) { 
            
            // Thread.currentThread () method to get the current thread 
            System.out.println (Thread.currentThread () getName () +. I); 
        } 
    } 
    public  static  void main (String [] args) {
         // Create a thread object 
        the MyThread t1 = new new the MyThread ();
         // start threads 
        t1 .start (); 
    } 
}

Method Two: Implement Runnable interface to avoid the limitations of single inheritance easy to share resources

Package dome3; 

public  class MyRunble the implements the Runnable { 

    public  void RUN () {
         for ( int I = 0; I <10; I ++ ) { 
            System.out.println (I); 
        } 
    }     
    public  static  void main (String [] args) {
         // Create custom thread runnable implement the interface from the write method 
        MyRunble = My new new MyRunble ();
         // instantiate thread 
        the thread = T1 new new the thread (My);
         // start threads 
        t1.start (); 
    } 

}

State three threads

  

Package dome4; 

public  class Threadzhuangtai the implements the Runnable { 

    public  void RUN () { 
        System.out.println ( "threads are running" );
         the try { 
            the Thread.sleep ( 500 ); 
            System.out.println ( "thread is blocked state" ) ; 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
            System.out.println ( "interrupted threads" ); 
        } 
    } 
public  static  void  main (String [] args) {
    threadzhuangtai threadzhuangtai =new new Threadzhuangtai (); 
    System.out.println ( "thread is a new state" ); 
    the Thread T1 = new new the Thread (threadzhuangtai); 
    t1.start (); 
    System.out.println ( "thread in the ready state" ); 
} 
}

 Fourth, the thread's priority and Sleep

  Thread scheduling assignment means the right to use the CPU to a plurality of threads in a particular mechanism

  1. The thread's priority sleeping thread termination

Package dome5;
 public  class youixanji the implements the Runnable { 

    public  void RUN () {
         for ( int I = 0; I <10; I ++ ) { 
            System.out.println (Thread.currentThread () getName (). + ":" + I ); 
        } 
    }     
    public  static  void main (String [] args) {
         // create a custom thread runnable implement the interface from the write method
         // interface class instantiation implemented 
        youixanji = My new new youixanji (); 
        youixanji MY2 = new new youixanji () ;
        MY3 youixanji  =new new youixanji (); 
        youixanji MY4 = new new youixanji ();
         // instantiate thread instantiated class interface object placed in the thread constructor 
        the Thread = T1 new new the Thread (My, ". 1" ); 
        the Thread T2 = new new the Thread (MY2, "2" ); 
        the Thread T3 = new new the Thread (MY3, ". 3" ); 
        the Thread T4 = new new the Thread (MY4, ". 4" );
         // set the priority 
        t1.setPriority (Thread.MAX_PRIORITY); 
        t2.setPriority (Thread.MIN_PRIORITY); 
        
        
        // start the thread 
        
        t1.start ();
        t2.start (); 
        // thread to suspend other threads to run 4 
        the try { 
            t4.join (); 
        } the catch (InterruptedException E) {
             // the TODO Auto-Generated Block the catch 
            e.printStackTrace (); 
        } 
        t4.start () ; 
        // thread to sleep three five seconds 
        the try { 
            t3.sleep ( 5000 ); 
        } the catch (InterruptedException E) { 
            e.printStackTrace (); 
        } 
        t3.start (); 
        
    } 

}

  2. Thread the comity

Thread comity only possible but can not necessarily be achieved comity

Package dome6;
 / * 
 * Polite thread implementation 
 * / 
public  class Myrunnable the implements the Runnable {
     // if i == 3 is polite current thread CPU resources so that the 
    public  void RUN () {
         for ( int I = 0; I <10; ++ I ) { 
            . System.out.println (Thread.currentThread () getName () + "run" + I);
             IF (I ==. 3 ) { 
                to Thread.yield (); 
                System.out.println ( "thread polite" ); 
            } 
            the try { 
                the Thread.sleep ( 300 );
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Thread t1=new Thread(new Myrunnable(),"线程一");
        Thread t2=new Thread(new Myrunnable(),"线程二");
        t1.start();
        t2.start();
    }

}

Fifth, the problem of insecurity thread

  1. When multiple threads share a resource, not a thread to complete all operations, so that other threads to modify the data will cause the problem of insecurity data for this application in order to solve the problem to the synchronized keyword to achieve synchronization of threads

  2. The synchronization method to solve the problem:

package dome7;

public class Site implements Runnable {
    private int count = 10;// 剩余票数
    private int num = 0;// 第几张票
    boolean flag = true;

    public void run() {
        while (flag) {
            stie();

        }
    }

    public synchronized void stie() {
        if (count > 0) {
            count--;
            num++;
            System.out.println (. Thread.currentThread () getName () + "grab on" + NUM
                     + "tickets remaining:" + COUNT); 
            In Flag = to true ; 
        } the else { 
            In Flag = to false ; 

        } 

    } 
}

Create a test class

package dome7;

public class Test {
        public static void main(String[] args) {
            Site s=new Site();
            Thread t1=new Thread(s,"黄牛党");
            Thread t2=new Thread(s,"抢票代理");
            Thread t3=new Thread(s,"12306");
            t1.start();
            t2.start();
            t3.start();
}
}

  3. synchronization code blocks to solve the problem

public class Site implements Runnable {
    private int count = 10;// 剩余票数
    private int num = 0;// 第几张票
    boolean flag = true;

    public void run() {
        synchronized (this) {
            while (flag) {
            if (count > 0) {
                count--;
                num++;
                System.out.println(Thread.currentThread().getName() + "抢到了第" +NUM
                         + "tickets remaining:" + COUNT); 
                In Flag = to true ; 
            } the else { 
                In Flag = to false ; 

            } 
        } 
    } 
        }

Test category unchanged

  The same time, only one thread into the synchronized (this) synchronized block when one thread to access a synchronized (this) synchronized block when multiple concurrent threads access the same resource block synchronization code, other synchronized (this) is also synchronized block when a thread is locked access a synchronized (this) when the sync block, other threads can access the resource is non-synchronized (this)

 

Reproduced in: https: //www.cnblogs.com/wuxuewei/p/11027963.html

Guess you like

Origin blog.csdn.net/weixin_34302561/article/details/93641260