Java---Multithreading---Meet it

Thread creation:

method 1:

    Override the run method by subclassing Thread.

public class MyThread extends Thread{

	@Override
	public void run() {
		System.out.println("MyThread overrides the run method by inheriting Thread");
	}
}

Method 2:

    By implementing the Runnable interface and implementing the run method.

public class MyRun implements Runnable{

	@Override
	public void run() {
		System.out.println("MyRun implements the run method of the Runnable interface");
	}

}

Scheduling of multiple threads:

Java's multithreading is a preemptive way of running.

setPriority()

    Set the priority of the thread, the lowest is 1, the highest is 10, the default is 5.

sleep()

The sleep() method of the Thread class operates on the current thread and is a static method. The argument to sleep() specifies the thread sleep time in milliseconds. The thread will not resume execution before this time unless it resumes early because of an interruption.

interrupt()

A thread can call another thread's interrupt() method, which will issue an InterruptedException to the suspended thread. In disguise, it functions to wake up the suspended thread. The method interrupt() of the Thread class is a forced wake-up technique.

public class Demo {
	public static void main(String[] args) {
		MyThread t1 = new MyThread(1);
		MyThread t2 = new MyThread(2);
		//setPriority() is relative scheduling
// t1.setPriority(5);
// t2.setPriority(2);
		
		
		t1.start();
		t2.start();
		
		try {
			Thread.sleep(1000);
			t1.interrupt();//Force wake up
		} catch (InterruptedException e) {
			e.printStackTrace ();
		}
	}
}
class MyThread extends Thread{
	private int start;

	public MyThread(int start) {
		this.start = start;
	}
	
	@Override
	public void run() {
		if (start==1) {
			try {
				Thread.sleep(3000);//Sleep for 3 seconds
			} catch (InterruptedException e) {
				System.out.println("I was kicked up!!");
			}
		}
		for (int i = start; i < 100; i+=2) {
			System.out.print(i+" ");
		}
		System.out.println();
	}
}

yield()

    Used to give threads with the same priority a chance to execute. If another thread with the same priority is runnable, yield() will put the thread into the runnable pool and make the other thread run. If there are no runnable threads of the same priority, do nothing.
    Note that when the yield() method is executed once, the thread just gives up the current opportunity, and then it will re-occupy the CPU with other threads, which is likely to be preempted by other threads.

join()

    Call this method of a thread to "merge" the current thread with the thread, that is, wait for the thread to end, and then resume the running of the current thread. It can realize the function of thread merging and is often used for absolute scheduling of threads.

//yield() must be scheduled between threads of the same priority
/*
 * yield() is to actively give an opportunity to other threads of the same priority,
 * Invalid if there are no other threads of the same priority.
 *
 * Note that after yield() gives up a chance, it must have the same priority as other
 * The thread will grab the opportunity again, and it will not be allowed to grab it again.
 *
 */

public class ScheduleDemo {

	public static void main(String[] args) {
		
		Thread t1 = new MyRun(1);
		Thread t2 = new MyRun(2);
		
		t1.start();
		t2.start();
		
		try {
			t1.join();//Incorporate t1 into the current thread---absolute scheduling
		} catch (InterruptedException e) {
			e.printStackTrace ();
		}
		
		for(int i=1000;i<1051;i++){
			System.out.print(i+" ");
		}
		System.out.println();
		
	}

}

class MyRun extends Thread{
	private int start;
	
	public MyRun(int start) {
		this.start = start;
	}

	@Override
	public void run() {
		
		for(int i=start;i<100;i+=2){
//			if(start==2){
// yield(); //relative dispatch
//			}
			System.out.print(i+" ");
		}
		System.out.println();
	}
	
}

wait()

    The current thread enters the wait pool of the object

notify()/notifyAll()

Wake up one/all waiting threads in the object's wait pool

The following 4 classes demonstrate wait(), notify() and notifyAll()

public class Buffer {
	private int value;//shared variable
	
	private boolean isEmpty=true;//Semaphore---mark
	
	//Production
	public synchronized void put(int i){ //The lock of the synchronized method is the owner of the method (non-static methods belong to this object, static methods belong to classes), in this case this is
		while(!isEmpty){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
		value = i;//production
		isEmpty=false;
		notify();//Notify a randomly selected thread in the waiting pool
		//notifyAll(); //Notify all threads in the waiting pool (those threads that share the same lock with the current thread)
	}
	
	//Consumption
	public synchronized int get(){
		while(isEmpty){
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
		
		isEmpty=true;
		notify();
		
		return value;
	}
}
public class Sender extends Thread {
	private Buffer buf;
	public Sender(Buffer buf) {
		this.buf = buf;
	}

	@Override
	public void run() {
		for(int i=1; i<=8; i++){
			buf.put(i);
			System.out.println("Sender put:" + i);
			
			try {
				sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
	}
}
public class Receiver extends Thread{
	private Buffer buf ;

	public Receiver(Buffer buf) {
		this.buf = buf;
	}
	
	public void run() {
		for(int i=1;i<=8;i++){
			System.out.println("Receiver get:"+ buf.get() );
			try {
				sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace ();
			}
		}
	}
}

Difference between wait/notify and sleep methods

wait and notify can only be used within the synchronized block of     the instance they are called on , while sleep() can be used everywhere .

The biggest difference between     wait() and sleep() : sleep() does not release the object lock , while wait() will release it, so the wait() method is better in terms of efficiency .

Creating a thread is not the same as starting a thread

    A thread doesn't actually start executing until a thread calls the start() method on the new thread's Thread object. A Thread object exists before its thread actually starts, and it still exists after its thread exits. Therefore, it is still possible to control or obtain information about a thread that has been created, even if the thread has not been started or has completed.

end thread

A thread ends in one of three ways:

1) The thread reaches the end of its run() method, which is recommended, and ends naturally.
2) The thread throws an uncaught Exception or Error.
3) Another thread calls a deprecated stop() method.

Daemon thread (referred to as daemon thread)

    We mentioned that a Java program exits when all its threads are done, but this is not entirely true because there are also system threads hidden in the program.
    It starts with the program startup, and captures the processing that meets its conditions during operation. Such a thread is a daemon thread.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325523519&siteId=291194637