Ali interviewer: You don’t even know how to say java multithreading, why would I ask you to come in?

Methods of creating threads

  • Inherit the Thread class

  • Inherit the Thread class, rewrite the run method, and start the thread through the thread class instance.start() method.

public class TestThread1 extends Thread{
    @override
    public void run(){
        System.out.println("线程run方法!");
    }
    
    public static void main(String){
        new TestThread1().start();
    }
}

  • Implement Runnable interface

  • Implement the Runnable interface, rewrite the run method, and start the thread through **new Thread (thread class instance).start()**

  • This method is recommended to avoid the limitations of java single inheritance

public class TestThread2 implements Runnable{
	@Override
	public void run() {
		System.out.println("线程run方法!");
	}
	
	public static void main(String[] args) {
		new Thread(new TestThread2()).start();
	}
}


  • Implement the Callable interface

  • Implement Callable interface, rewrite call method, call method has return value

  • Start method:

  • Create execution service

  • Submit for execution

  • Get results

  • Close service

public class TestThread2 implements Callable{
	@Override
	public Boolean call() {
		System.out.println("线程call方法!");
		return true;
	}
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		
		TestThread2 t1 = new TestThread2();
		TestThread2 t2 = new TestThread2();
		TestThread2 t3 = new TestThread2();
		//创建执行服务
		ExecutorService ser = Executors.newFixedThreadPool(3);
		//提交执行
		Future<Boolean> r1 = ser.submit(t1);
		Future<Boolean> r2 = ser.submit(t2);
		Future<Boolean> r3 = ser.submit(t3);
		//获取结果
		boolean rs1 = r1.get();
		boolean rs2 = r2.get();
		boolean rs3 = r3.get();
		//关闭服务
		ser.shutdownNow();
	}

Thread synchronization

  • Multiple threads operate the same resource at the same time, threads are not safe, and variable values ​​are disordered

  • Lock

  • Queue + lock (synchronized)

  • Synchronized default lock this, you can display the specified lock object to modify

1. Synchronized modification method, thread safe method

public class TestThreadSafe {

    public static void main(String[] args) {
        BuyTicket bt1 = new BuyTicket();

        Thread thread1 = new Thread(bt1,"张三");
        Thread thread2 = new Thread(bt1,"李四");
        Thread thread3 = new Thread(bt1,"黄牛");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNumber = 10;

    private boolean flag = true;

    @Override
    public void run() {
        while(flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void buy() throws InterruptedException {
        //买票
        if(ticketNumber <= 0){
            System.out.println("票卖完了!");
            flag = false;
            return;
        }
        Thread.sleep(100);
        //Thread.yield();
        System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");
    }
}

2. Synchronized modified code block, thread safe code block

public class TestThreadSafe {

    public static void main(String[] args) {
        BuyTicket bt1 = new BuyTicket();

        Thread thread1 = new Thread(bt1,"张三");
        Thread thread2 = new Thread(bt1,"李四");
        Thread thread3 = new Thread(bt1,"黄牛");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNumber = 10;

    private boolean flag = true;

    @Override
    public void run() {
        while(flag) {
            System.out.println(Thread.currentThread().getName() + "准备买票" + flag);
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void buy() throws InterruptedException {
        synchronized(this){
            //买票
            if(ticketNumber <= 0){
                flag = false;
                System.out.println("票卖完了!");
                return;
            }
            Thread.sleep(100);
            //Thread.yield();
            System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");
        }
    }
}

3. Use ReentrantLock

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {

    public static void main(String[] args) {
        BuyTicket bt1 = new BuyTicket();

        Thread thread1 = new Thread(bt1,"张三");
        Thread thread2 = new Thread(bt1,"李四");
        Thread thread3 = new Thread(bt1,"黄牛");

        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNumber = 1000;

    private boolean flag = true;

  //定义可重复锁
    private	final ReentrantLock lock = new ReentrantLock();
    
    @Override
    public void run() {
        while(flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void buy() throws InterruptedException {
        	lock.lock();
            //买票
            if(ticketNumber <= 0){
                System.out.println("票卖完了!");
                flag = false;
            }else {
            	Thread.sleep(100);
                //Thread.yield();
                System.out.println(Thread.currentThread().getName() + "买到了一张票,还剩下"+(--ticketNumber) + "张票!");
            }
            lock.unlock();
    }
}


  • Deadlock

  • For more than two object locks, each thread occupies the resources needed by each other. Form a deadlock.

Thread state

  • Freshman status (new)
  • Ready state (start)
  • Blocking state (sleep, wait, synchronization lock)
  • Operating status
  • After the dead state thread object enters the dead state, it cannot call the start() method again to start again

Thread (Thread class) method

  • setPriority(int newPriority) Change thread priority newPriority from 1 to 10

  • static void sleep(long millis) makes the currently executing thread sleep for the specified milliseconds without releasing the thread lock object

  • void join() Thread merge and wait for the thread to terminate

  • static void yield() Pause the currently executing thread and execute other threads

  • void interrupt() interrupt thread

  • boolean isAlive() is the thread alive

Daemon thread

  • setDaemon(true): set as a daemon thread

  • Threads are divided into user threads and daemon threads

  • JVM virtual machine ensures that user threads are executed

  • The JVM virtual machine does not have to wait for the daemon thread to finish executing

         eg:后台记录操作日志,监控内存,垃圾回收等待

At last

Thank you for seeing here. After reading, if you have any questions, you can ask me in the comment area. If you think the article is helpful to you, remember to give me a thumbs up. You will share java-related technical articles or industry information every day. Welcome everyone's attention and Forward the article!

Guess you like

Origin blog.csdn.net/weixin_47277170/article/details/108293878