Java_ Multithreading Basics

Custom thread

Method to realize

  1. Thread class inheritance
  2. Implement Runnable

Thread class inheritance

  • After inheriting Thread, to override the run method
  • void public RUN task method body for the thread to be executed
  • Method to start a thread for the Start () , instead of calling run ()
  • Call the run method can not open a new thread, just an ordinary function call
  • Thread of the life cycle of the class can only be activated once
    public class xiancheng2 {

    public static void main(String[] args) {
            
        //创建对象
        Myrun  run1 =  new Myrun();
        //创建线程对象
        Thread  runTd = new Thread( run1 );
        // 开启线程
        runTd.start();
        run1.say();
    }
}

class Myrun extends Thread{
    @Override
    public void run() {
        System.out.println("新的线程");
    }
    
    public void say() {
        System.out.println( "美好的一天" );
    }
    
}

Common API

String getName() Returns the name of this thread.
long getId() Returns the identifier of the thread.
int getPriority() Returns the priority of the thread.
Thread.State getState() Returns this thread's state.
join() Waits for this thread.
join( long millis ) Wait for this thread to a maximum of millis milliseconds.
static void sleep(long millis ) The currently executing thread to sleep in a specified number of milliseconds (suspended).
void start()
void interrupt() Interrupt thread.
static boolean interrupted() Tests whether the current thread has been interrupted.
boolean isDaemon() Tests if this thread is a daemon thread.

Implement Runnable

  • The method that is similar to the inherited Tread:

    • Inheritance Runnable interface, run method
    • Create a thread object, open thread

difference

  1. By way interface, more flexible (Java is a single inheritance)
  2. Inheritance way easier. (Rarely used)

Thread State

  1. A thread generally through five states
    • New Status
    • Readiness
    • Operating status
    • Wait / blocked
      • Sleep: Calling sleep ()
      • Obstruction:
      • Pending: The call to suspend suspend, resume () off-hold (not recommended)
      • Wait: call wait ()
    • Death state

Use thread

Sleeping

  • Call sleep method allows the thread to sleep for a specified time before waking to enter the ready state,

    • public static void sleep( long millis) throw InterruptedException

    • public static void sleep( long millis , int nanos) throw InterruptedException

public class xiancheng2 {
    public static void main(String[] args) throws InterruptedException{
            
        //创建对象
        Myrun  run1 =  new Myrun();
        //创建线程对象
        Thread  runTd = new Thread( run1 );
        Thread  runTd2 = new Thread( run1 );
//       开启线程
        runTd.start();
        //使主线程睡眠100ms
        Thread.sleep(100);  
        System.out.println( "美好的一天" );
    }
}

class Myrun implements Runnable{
    
    @Override
    public void run() {
        System.out.println("新的线程");
        try {
            // 使该线程睡眠100ms
            Thread.sleep(100);  
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

Thread priority

  • In Java thread's priority is represented by an integer between 1 and 10. The higher the value, the higher the priority. The default is 5
  • Not suitable for regulating the details thread

  • The main thread priority defaults to 5. Child thread priority same initial value as the parent thread.

  • :( can not change the priority precise)

    • public final void setPriority( int newPriority )

public class xiancheng2 {
    public static void main(String[] args) {
            
        //创建对象
        Myrun  run1 =  new Myrun(1);
        Myrun  run2 =  new Myrun(2);
        //创建线程对象
        Thread  runTd1 = new Thread( run1 );
        Thread  runTd2 = new Thread( run2 );
        //设置优先级
        runTd2.setPriority( Thread.MIN_PRIORITY );//最高的优先级
        runTd1.setPriority( Thread.MAX_PRIORITY );//最低的优先级
        //开启线程
        
        runTd2.start();
        
        runTd1.start();
        
    }
}
class Myrun implements Runnable{
    private  int id ;
    public Myrun(int id) {
        this.id = id;
    }
    @Override
    public void run() {
        System.out.println("新的线程"+ this.id);
    }
    
}

Thread concessions

  1. classification
    • Just let the current thread CPU resources, who can not give specific CPU will determine (no guarantee)
    • Thread will give concessions specified thread, the specified thread is not completed, it will not resume execution (threads merged - guaranteed)
  2. yield method

    • The thread is currently running to make a CPU, back to the ready state. (Insecurity)

      • pubic static void yield()

  3. join method

  • Call to join the thread executing the method, after the resumption of other threads

    • public final void join( ) throw InterruptedException

    • public final void join( long millis) throw InterruptedException

    • public final void join( long millis ,int nanos ) throw InterruptedException

public class xiancheng2 {
    public static void main(String[] args) throws InterruptedException{
            
        Thread  run1 =  new Myrun("先");
        Thread  run2 =  new Myrun("后");
        
        run2.start();
        run2.join();    //run2线程将执行完后,在恢复其他线程。
        
        run1.start();
        for (int i = 0; i < 50; i++) {  
            System.out.print(6);
        }
    }
}
class Myrun extends Thread{
    private  String id ;
    public Myrun(String id) {
        this.id = id;
    }
    @Override
    public void run() {
        try {
            
        } catch (Exception e) {
            // TODO: handle exception
        }
        for(int  i=100 ;i>0;i--) {
            System.out.print(this.id);
        }
    }
}   

Note (there are parameters)



如果A线程中掉用B线程的join(10),则表示A线程会等待B线程执行10毫秒,10毫秒过后,A、B线程并行执行。
需要注意的是,jdk规定,join(0)的意思不是A线程等待B线程0秒,而是A线程等待B线程无限时间,直到B线程执行完毕,即join(0)等价于join()。                     
                                                                            摘自:https://www.cnblogs.com/ldq2016/p/9045551.html

Thread guard

  • Thread running in the background (memory management, thread scheduling ...) called daemon threads
  1. Development daemon thread

    • public final void setDaemon (boolean on) // on whether to represent a daemon thread (fal se: ordinary thread)

      • In java: But after the foreground thread (common thread) are running, quit the program
        • And returned to Taiwan program is run completely unrelated.

Thread Synchronization

Synchronization method

  • Synchronized with the synchronization method refers to a modified method of

    • synchronized <return type> method name ([parameter list]) [the throw exception] {

      }

      • Static lock object synchronization method is as follows: the current class of objects
      • Lock the object non-static synchronized method is: this
      • When the thread goes to sleep or get concessions after lock lock, the lock sleep together with a concession.
      • After synchronization method exits, the lock is released, waiting for the other thread can acquire the lock.
      • Synchronization will reduce concurrency multithreading.
public class tridet {

    public static void main(String[] args) {
        
        Ticket tck = new Ticket();
        Thread t2 = new Thread(tck,"window1");
        Thread t1 = new Thread(tck,"window2");
        Thread t3 = new Thread(tck,"window3");
        System.out.println( "tck: " + tck );
        t1.start();
        t2.start();
        t3.start();
    }
}

class Ticket implements Runnable{
    private  int  TicketNum = 100;
    
    public void run() {
        while( this.TicketNum>0 ) {
            this.buy();
        }
    }
    
    public synchronized void buy() {
        System.out.println( this );  // this ==> tck(锁对象)
        if(this.TicketNum-->0) 
            System.out.println(Thread.currentThread().getName() + "买出一张票,还剩:" + this.TicketNum   );
    }
}

Synchronization scheduling method

final void wait() Make a thread into a wait state. Until another thread calls notify or notifyAll method to wake up
final void wait(long timeout) timeout milliseconds to make a thread enters a wait state until the wait time, or to wake up.
final void notify() Wake up a thread waiting for the pool (no guarantee, wake up not sure which one thread)
final void notifyAll() Wake up all threads waiting in the pool

Synchronization statement block

synchronized (lock object) {}

  • Lock the object to be unique
    • Lock object like a key in his custody, then they would have to make to ensure synchronization ensures that only one thread execution when finished synchronization block of statements (return of keys) other threads to enter the synchronized block of statements, all those who want to keep the only key (key only one).
public class tridet {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Thread t2 = new Ticket("window2");
        Thread t1 = new Ticket("window1");
        Thread t3 = new Ticket("window3");
        t1.start();
        t2.start();
        t3.start();
        
    }
}

class Ticket extends Thread{
    private static int  TicketNum = 10;
    private static Object  look = new Object(); // 锁对象(唯一)
    
    public void run() {
        while( this.TicketNum > 0 ) {
            synchronized (look) {
                if(this.TicketNum--<=0) break;
                System.out.println(getName() + "买出一张票,还剩:" + this.TicketNum   );
            }   
        }
    }
    
    public Ticket(String name) {
        super(name);
    }
}

public class tridet {

    public static void main(String[] args) {
        
        Ticket tck = new Ticket();
        
        Thread t2 = new Thread(tck,"window1");
        Thread t1 = new Thread(tck,"window2");
        Thread t3 = new Thread(tck,"window3");
        t1.start();
        t2.start();
        t3.start();
        
    }
}

class Ticket implements Runnable{
    private  int  TicketNum = 100;
    
    public void run() {
        while( this.TicketNum > 0 ) {
            synchronized (this) {   //锁对象为this , 即:tck对象(唯一)
                if(this.TicketNum--<=0) break;
                System.out.println(Thread.currentThread().getName() + "买出一张票,还剩:" + this.TicketNum   );
            }   
        }
    }
}

Deadlock

  • Each object is waiting for the other to release the resource lock.

public class shisuo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Object oj1 = new Object();
        Object oj2 = new Object();
        
        boy b1 = new boy( oj1 , oj2 );
        girl g1 = new girl( oj1 , oj2 );
        
        Thread thread1 = new Thread(b1,"boy");
        Thread thread2 = new Thread(g1,"boy");
        
        thread1.start();
        thread2.start();
    }
}

class boy implements Runnable {
    private Object look1, look2;
    public boy(Object look1, Object look2) {
        super();
        this.look1 = look1;
        this.look2 = look2;
    }
    public void run() {
        synchronized (look1) {
            System.out.println("body");
            synchronized (look2) {
                System.out.println("body2");
            }
        }
    }
}

class girl implements Runnable {
    private Object look1, look2;
    public girl(Object look1, Object look2) {
        super();
        this.look1 = look1;
        this.look2 = look2;
    }
    public void run() {
        synchronized (look2) {
            System.out.println("girl");
            synchronized (look1) {
                System.out.println("girl2");
            }
        }
    }
}

volatile keyword

  • Role: The process does not allow one thread operating in its member variable modified, another thread insert operation.

  • This keyword is only allowed to modify the member variables, local variables can not be modified.
    • Local variables can not be two threads simultaneously

Guess you like

Origin www.cnblogs.com/zoukun/p/12275832.html