Java Threads create threads

Process and threads

Process

  • A process runs isolated from other processes
  • A process cannot directly access shared data in other processes
  • The resources of the process, e.g. memory and CPU time, are allocated to it via the operating system
  • Example: Java Virtual Machine is a process

Thread

  • A thread is a lightwight process
    • Each has its own stack
    • Can access shared data of other threads in the same process
    • Every thread has its own memory cache
    • If a thread reads shared data, it stores this data in its own memory cache.A thread can re-read the shared data

Key Concepts in concurrent programming

Atomicity

  • Cannot be interrupted
  • Once it starts is always completes
  • One example assignment a=5

Visibility

What is visibility between threads?
The modification of a shared variable value by a thread can be seen by other threads in time.
Visibility between threads

Order of execution

The order in concurrent programming is not guaranteed!

Critical code

A part of code that must be executed by a single thread at one time

Two ways of creating a thread

Creating a thread by implements


public class MyFirstRunnable implements Runnable
{
    
    
    public void run(){
    
    //implement the abstract run() method of the runnable interface
        System.out.println("Thread");
    }
}

MyFirstRunnable xyz = new MyFirstRunnable();
Thread thread = new Thread(xyz);
thread.start();

You can use the same runnable several times

Runnable runnable = new MyFirstRunnable();

for(int i =0;i<25;i++>){
    
    
    new Thread(runnable).start();
}

//How many threads will be running?
//26 together with the main thread

Creating a thread using extends

public class MyThread extends Thread{
    
    
    public void run(){
    
    //override the run() method
        System.out.println("MyThread running");
        System.out.println("do some interesting stuff");
		System.out.println("Leaving thread using MyThread extends Thread");
    }

    public static void main(String[] args) {
    
    
		// This approach uses a class the extends Thread
		MyFirstThreadExtend myFirstThreadExtend = new MyFirstThreadExtend();
		myFirstThreadExtend.start();
	}
}

Give names to a Thread

public class Order implements Runnable {
    
    
    public void run() {
    
    
    String threadName = Thread.currentThread().getName();
    System.out.println("I'm running in thread‐" + threadName);
    }

    public static void main(String[] args) {
    
    
    Order order = new Order();
        for (int i = 0; i < 25; i++) {
    
    
        Thread thread = new Thread(order);
        thread.setName("Thread " + i);
        thread.start();
        }
    }
}

One of the results:

I'm running in thread-Thread 0
I'm running in thread-Thread 2
I'm running in thread-Thread 4
I'm running in thread-Thread 3
I'm running in thread-Thread 6
I'm running in thread-Thread 1
I'm running in thread-Thread 7
I'm running in thread-Thread 9
I'm running in thread-Thread 10
I'm running in thread-Thread 11
I'm running in thread-Thread 5
I'm running in thread-Thread 12
I'm running in thread-Thread 16
I'm running in thread-Thread 18
I'm running in thread-Thread 14
I'm running in thread-Thread 15
I'm running in thread-Thread 19
I'm running in thread-Thread 8
I'm running in thread-Thread 13
I'm running in thread-Thread 17
I'm running in thread-Thread 22
I'm running in thread-Thread 24
I'm running in thread-Thread 21
I'm running in thread-Thread 20
I'm running in thread-Thread 23

When the java virtual machine (also known as JVM) executes the main method, it will find the operating system (that is, os) to open a path from the main method to the cpu. This path is the main thread, which is the so-called main Thread.

Then the cpu can execute the main method through this thread, which is the path.

When we new a thread object, this time opens up a path to the cpu, and this path is used to execute the run method.

Now for cpu, he has two execution paths, cpu has the right to choose, cpu he likes, which path will be executed, we can not control the cpu, all there will be random Printed result.

Conversely, two threads, a main thread, and a new thread, they grab the execution right of the cpu together (that is, the execution time of the cpu), and whoever grabs it will execute it first.

Inline definition

inline:

Thread t = new Thread(new Runnable()
{
    
     public void run() {
    
     /*stuff here*/ } });
t.start();

Difference between mythread.run() and mythread.start()

Thread.start and Thread.run in Java

start(): Its function is to start a new thread, and the new thread will execute the corresponding run() method. start() cannot be called repeatedly.
run(): run() is the same as a normal member method and can be called repeatedly. If you call run() alone, run() will be executed in the current thread without starting a new thread.

// Demo.java 的源码
class MyThread extends Thread{
    
    
    public MyThread(String name) {
    
    
        super(name);
    }

    public void run(){
    
    
        System.out.println(Thread.currentThread().getName()+" is running");
    }
};

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        Thread mythread=new MyThread("mythread");

        System.out.println(Thread.currentThread().getName()+" call mythread.run()");
        mythread.run();

        System.out.println(Thread.currentThread().getName()+" call mythread.start()");
        mythread.start();
    }
}

operation result:

main call mythread.run()
main is running
main call mythread.start()
mythread is running

Result description:
(01) Thread.currentThread().getName() is used to obtain the name of the "current thread". The current thread refers to the thread being scheduled for execution in the cpu.
(02) mythread.run() is called in the "main thread main", and the run() method runs directly on the "main thread main".
(03) mythread.start() will start "thread mythread". After "thread mythread" is started, the run() method will be called; at this time, the run() method is running on "thread mythread".

sleep method

  • Only make current thread sleep
  • Sleep for a certain milliseconds
  • Syntax: Thread.sleep(996)
  • The thread will pause(suspend)
  • Free up CPU time for other threads
public void run(){
    
    
    try{
    
    
    Thread.sleep(1000);
    }
    catch(InterruptedException e){
    
    
    e.printStackTrace();
    }
}

InterruptedException

  • This exception is thrown when a thread is interrupted
  • Enables you to deal with the interrupt elegantly
  • Another thread might needs resources

How to interrupt a thread

thread.interrupt sets the interrupted flag
Blocking methods, such Thread.sleep(), try to detect when a thread has been interruptd and return early
They respond to interruption by clearing the setting the flag to false and throwing InterruptedException.
Interrupting a thread that is not live need not have any effect.

  • If any thread is in sleeping or waiting state (i.e. sleep() or wait() is
    invoked), calling the interrupt() method on the thread, breaks out the
    sleeping or waiting state throwing InterruptedException.
  • If the thread is not in the sleeping or waiting state, calling the
    interrupt() method performs normal behaviour and doesn't interrupt
    the thread but sets the interrupt flag to true.
    When a thread is waiting, sleeping, or occupied, that is Blocked state, and this type of error will be thrown when the thread is interrupted. After Java6, the method to end a thread A is A.interrupt(). If the thread is in a non-blocking state, for example, when the thread is executing some code, it is interrupted, then the interrupt variable of the thread will be set to true, telling others that the thread is interrupted, and there will be no interruptedException. . But if the thread is blocked at this time, for example, it is sleeping, then this error will be thrown. Please note that the variable interrupt is set to false at this time. It is best to consider this flag when writing code.
public void interrupt()
public static boolean interrupted()
public boolean isInterrupted()

Yield

  • The executing thread is suspended
  • The CPU is given to some other runnable thread
  • This thread will wait until the CPU becomes available again
    Technically, in process scheduler’s terminology,
    • the executing thread is returned to the ready queue of the processor and
    • waits for its next turn. The
      yield method
      Thread.yield() method in the Java thread is translated as thread concession. As the name implies, it means that when a thread uses this method, it will give up its CPU execution time.

Let yourself or other threads run, pay attention to let yourself or other threads run, not simply let other threads.

The function of yield() is to yield. It allows the current thread to enter the "ready state" from the "running state", allowing other waiting threads with the same priority to obtain the right to execute; however, it cannot guarantee

It proves that after the current thread calls yield(), other threads with the same priority will definitely get the right to execute; it is also possible that the current thread enters the "running state" to continue running!

For example, a group of friends were queuing to get on the bus. When it was Yield's turn, he suddenly said: I don't want to go up first. Let's all race to get on the bus. Then everyone rushed to the bus together,

Maybe someone else got in the car first, or it could be that Yield got in the car first.

But threads have priority, the higher the priority, the first to get on the car? This is not necessarily true. People with high priority are only the first to get in the car with a higher probability.

In the end, the first person to get on the bus may also be the person with the lowest priority. And the so-called priority execution can only be reflected in a large number of execution times.

Interrupt

How to get a reference to yourself as a thread…

public class MyThread implements Runnable{
    
    
    public void run(){
    
    
        Thread.currentThread().interrupt();
        //If implements Runnable eed to use 
        //Thread.currentThread()
    }
}

wait(), notify(), notifyAll()

The difference between sleep() and wait() The difference between
sleep and wait, does wait throw an exception?

  1. sleep(long millis) is a static method of Thread, which is used to specify the sleep time for the thread. During this period, the synchronization lock is not released, and the thread execution is resumed when the time is reached; wait() is the final method of Object, which will suspend the caller thread. At the same time, release the lock until it is awakened or timed out by methods such as notify/notifyAll, and then compete for CPU with other threads.

  2. The main thing is that sleep() does not release the synchronization lock, while wait() releases the synchronization lock, so that other threads can use the synchronization control block or method.

  3. wait, notify, and notifyAll can only be used in synchronous control methods or synchronous control blocks, while sleep can be used anywhere.
    Methods wait, notify and notifyAll may only be called when the current thread has a lock on the object (ie, from within a synchronized method or from within a method that has been called by a synchronized method).

  4. Sleep, wait must catch exceptions, and notify and notifyAll do not need to catch exceptions.

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-wwwTVMck-1601130275367)(https://s1.ax1x.com/2020/09/22/wOWj3D.png )]

Since there is no way of specifying which thread is to be woken, this is only really appropriate if there is only one waiting thread.
If all threads waiting for a lock on a given object are to be woken, then we use notifyAll.
This wait() method should only be called by a thread that is the owner of this
object’s monitor.

public final void wait()
• Exception
• IllegalMonitorStateException − if the current thread is not the owner
of the object’s monitor.
• InterruptedException − if another thread has interrupted the current
thread. The interrupted status of the current thread is cleared when
this exception is thrown.

Homework for lesson1

  1. Write a Java Thread using both methods that:
    Loops 100 times printing “Hello World”
   public class HelloWorld implements Runnable{
    
    
	public void run() {
    
    
		System.out.println("hello");
	}
	
	public static void main(String[] args) {
    
    
		HelloWorld helloWorld = new HelloWorld();
		for(int i =0;i<100;i++) {
    
    
		Thread mythread = new Thread(helloWorld);
		mythread.start();
		}
	}
}
public class HelloWorld extends Thread{
    
    
	public void run() {
    
    
		int i=0;
		while(i<100) {
    
    
			//print hello
			System.out.println("hello");	
			//counter++
			i++;	
		}	
	}
	
	public static void main(String[] args) throws InterruptedException {
    
    
		
		//prepare the thread
		HelloWorld helloWorld = new HelloWorld();
		
		//Start the thread
		helloWorld.start();
		
	}
	
}
  1. Make the thread sleep for 1 second between each iteration
public class HelloWorld implements Runnable{
    
    
	public void run() {
    
    
		int i=0;
		while(i<100) {
    
    
			
			//sleep 1s
			try {
    
    
				Thread.sleep(1000);
			} catch (InterruptedException e) {
    
    
				e.printStackTrace();
			}
			
			//print hello
			System.out.println("hello");
			
			//counter++
			i++;	
		}	
	}
	
	public static void main(String[] args) throws InterruptedException {
    
    
		
		//prepare the thread
		HelloWorld helloWorld = new HelloWorld();
		Thread mythread = new Thread(helloWorld);
		
		//Start the thread
		mythread.start();
		
	}
	
}
  1. Write code to interrupt the thread so that it finishes early
public class HelloWorld implements Runnable{
    
    
	public void run() {
    
    
		while(true) {
    
    	
			System.out.println("hello");	
			if(Thread.currentThread().isInterrupted()==true) {
    
    
				System.out.println("Terminated!");
				break;
			}
			
		}	
	}
	
	public static void main(String[] args) throws InterruptedException {
    
    
		
		//prepare the thread
		HelloWorld helloWorld = new HelloWorld();
		Thread mythread = new Thread(helloWorld);
		
		//Start the thread
		mythread.start();
		
		//Run some rubbish code
		for(int i=0;i<1000000;i++) {
    
    
		int ii=1000;
		}
		
		//Interrupt
		mythread.interrupt();
		
	}
	
}

Guess you like

Origin blog.csdn.net/GreatSimulation/article/details/108818433