Detailed Java-based multi-threading

 

Java multithreading is preemptive. Whoever has the highest priority will execute it first.

Java uses the java.lang.Thread class to represent threads , and all thread objects must be instances of the Thread class or its subclasses.

Thread class

Construction method:  

public Thread(): Allocate a new thread object.

public Thread(String name): Allocate a new thread object with a specified name.

public Thread(Runnable target): Allocate a new thread object with the specified target.

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

Common methods:

public String getName(): Get the current thread name.

public void start(): Cause this thread to start execution; the Java virtual machine calls the run method of this thread.

public void run(): The task to be executed by this thread is defined here.

public static void sleep(long millis): Suspend the currently executing thread for the specified number of milliseconds (temporarily stop execution).

public static Thread currentThread(): Returns a reference to the currently executing thread object.

public void Join() terminate the thread

Steps to create and start multithreading

One, use the base class Thread

1. Define a subclass of the Thread class and rewrite the run() method of this class. The method body of the run() method represents the task that the thread needs to complete, so the run() method is called the thread execution body.

2. Create an instance of the Thread subclass, that is, create a thread object

3. Call the start() method of the thread object to start the thread

public class MyThread extends Thread{
	@Override
	public void run() {
		for( int i = 0;i < 20;i++){
			System.out.println("run"+i);
		}
	}
}
public static void main (String[]args){
	//多线程
	MyThread my1 = new MyThread();
	//my1.run();调用run()方法     单线程
	my1.start();//执行run()方法   多线程   新开一个栈空间
	//main执行
	for(int i  = 0;i < 20;i++){
		System.out.println("main"+i);
	}
}

Second, use the Runnable interface

1. Define the implementation class of the Runnable interface and rewrite the run() method of the interface. The method body of the run() method is also the thread execution body of the thread.

2. Create an instance of the Runnable implementation class, and use this instance as the Thread target to create a Thread object, which is the real thread object.

3. Call the start() method of the thread object to start the thread

public class DemoRunnableImpl implements Runnable{//步骤一
	@Override
	public void run(){
		for(int i = 0;i < 5;i++){
			System.out.println(Thread.currentThread().getName()+"-->"+i);
		}
	}
}
public static void main (String[] args){
	DemoRunnableImpl demo =new DemoRunnableImpl();//步骤二
	Thread thread= new Thread (demo);
	thread.start();//步骤三
}

Third, use anonymous inner classes

public static void main(String[] args){
	//线程的父类是Thread
	new  Thread(){
		@Override
		public void run(){
			for(int i = 0;i < 5;i++){
				System.out.println(Thread.currentThread().getName()+"小小张自由");
			}
		}
	}.start();
	//线程的接口是Runnable
	Runnable r = new Runnable(){
		@Override
		public void run(){
			for(int i = 0;i < 5;i++){
				System.out.println(Thread.currentThread().getName()+"身体健康");
			}
		}
	};
	new Thread(r).start();
}

Solve thread safety issues

Thread safety issues are caused by global variables and static variables. If each thread has only read operations on global variables and static variables, but no operations, in general, this global variable is thread-safe.

If multiple threads perform write operations at the same time, thread synchronization generally needs to be considered. Otherwise, thread safety may be affected.

The synchronized keyword can be used in a block in a method, which means that only mutually exclusive access is performed on the resources of this block.

The lock object can be of any type. Multiple thread objects use the same lock. At any time, at most one thread running has a synchronization lock, whoever gets the lock enters the code block, and other threads can only wait.

One, synchronization code block

//语法格式
synchronized(同步锁){
	//需要同步操作的代码
}
//示例
private int cont = 100;
Object obj = new Object();
@Override
public void run(){
	synchronized(obj){ //被锁住的代码
		while(cont>0){
			//线程休眠10毫秒
			try{
				Thread.sleep(10);
			}catch(Exceptione){
				System.out.println(e.getMessage());
			}
			System.out.println(Thread.currentThread().getName()+"正在抢第"+cont+"票");
			cont--;
		}
	}
}

Two, synchronization method

Extract the code that needs to be synchronized. Put it in a method. Run() method then calls synchronous method

public synchronized void method(){ 
	//可能会产生线程安全问题的代码 
}

3. Lock mechanism

     1. Create a ReentrantLock object at the member location

     2. Call the method Lock in the Lock interface before the code that may have security problems to obtain the lock

     3. After the code that may have security problems, call the method unLock in the Lock interface to release the lock

public class DemoRunnableImpl implements Runnable {
    private int cont = 100;
    Lock lock=new ReentrantLock();//创建一个ReentrantLock对象
    @Override
    public void run() {
        lock.lock();//获取锁
        while (cont > 0) {
            //线程休眠10毫秒
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            System.out.println(Thread.currentThread().getName() + "正在抢第" + cont + "票");
            cont--;
        }
        lock.unlock();//释放锁
    }
}

Communication between threads

    When the concurrent execution of multiple threads, default CPU is randomly switching threads , multiple threads when we need to have completed either a task, and we want them to have the implementation of the law , among so many threads require some coordination of communication , In order to help us achieve multi-threaded co-operation of a piece of data.

Overview of thread status

 Waiting and awakening cases-producers and consumers

        1. The customer and boss threads must be wrapped in a synchronous code block to ensure that only one of waiting and awakening can be executed

        2. The lock object used synchronously must be unique

        3. Only lock objects can use wait() and notify() methods

public static void main(String[] args) {
        Object obj=new Object();//锁对象
        //消费者
        new Thread(){
            @Override
            public void run() {
                while (true){
                    synchronized (obj){  //同步代码段
                        System.out.println("告知老板要的包子种类和数量");
                        try {
                            obj.wait();//线程等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //唤醒之后执行的代码
                        System.out.println("包子已经做好了,开吃!");
                    }
                }
            }
        }.start();
        //生产者
        new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(5000); //花5s做包子
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (obj){ //同步代码段
                        System.out.println("老板5秒钟包子做好了,可以吃包子了!");
                        //做好包子,调用notify方法,唤醒顾客吃包子
                        obj.notify();
                        System.out.println("---------------------");
                    }
                }
            }
        }.start();
    }

 Creation is not easy, if this blog is helpful to you, please remember to leave a message + like it.

Guess you like

Origin blog.csdn.net/promsing/article/details/112408018