On java in the thread

1.java way to create a thread

In java, there are three ways to create threads:

  1. Inherit the Thread class, override the run () method
  2. Implement Runnable interface, run () method
  3. Callable implement interfaces, and implements call () method

The following will mainly talk about the first two methods.

1. to create a thread through inheritance Thread class

Inherit the Thread class must override the run () method, run () method defined in the thread body, which is the entry point for the new thread. The only way to turn this thread by calling start (), if a direct call run () method and You can not open threads.

Example 1:

    public class ThreadDemo01 extends Thread{
    	//多线程的线程体
    	@Override
    	public void run() {
    		for(int i=1;i<=20;i++){
    			System.out.println("一遍吃饭...");
    		}
    	}
    	public static void main(String[] args) {
    		//开启多线程 创建线程
    		ThreadDemo01 th=new ThreadDemo01();
    		//开启线程
    		th.start(); 
    		//th.run();   注意:这是方法的调用,不是多线程的开启		
    		for(int i=1;i<=20;i++){
    			System.out.println("一遍说话...");
    		}
    	}
    }
复制代码

After executing th.start (), it will open this thread, which is written in the statement run () method in the statement.

Like having two cars run up in two lanes simultaneously and then open a new thread.

If you do not write code with thread, then only the run () method in the code behind the main method for loop, like two people over a narrow alley, a person can only follow a person walking.

In this way we can achieve write once again to speak to eat

2. to create a thread by implementing Runnable interface

By implementing Runnable interface to create a thread to avoid the limitations of single inheritance, and can share resources.

Example 2:

    public class ThreadDemo02 implements Runnable{
    	//定义线程体的方法,当被调用的时候,会逐行执行里面的代码
    	@Override
    	public void run() {
    		for(int i=1;i<=100;i++){
    			System.out.println("一边跑步...");
    		}
    	}
    	public static void main(String[] args) {
    		ThreadDemo02 th=new ThreadDemo02();
    		//开启线程//创建线程
    		Thread t=new Thread(th);  //因为开启线程的方法在Thread类中,Thread做为代理类出现
    		t.start();
    		for(int i=1;i<=100;i++){
    			System.out.println("一边听歌...");
    		}
    	}
    }
复制代码

Because the method is not turned on in the thread Runnable interface, so we need to use the Thread class as a proxy class, call the start () method, open thread.

3. Analog to buy train tickets through multi-threaded

Example 3:

    public class BuyTikets implements Runnable{
    	//车票
    	int tikets=20;
    	@Override
    	public void run() {
    		//循环买票
    		while(true){
    			if(tikets<=0){
    				break;
    			}
    			try {
    				Thread.sleep(200);  //线程睡眠100ms
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			System.out.println(Thread.currentThread().getName()+"正在购买第"+tikets--+"张票");
    		}
    	}
    	public static void main(String[] args) {
    		BuyTikets bt=new BuyTikets();
    		//开启三个线程
    		new Thread(bt,"张三").start();
    		new Thread(bt,"李四").start();
    		new Thread(bt,"王五").start();
    	}
    }
复制代码

As a result of the program:

    张三正在购买第20张票
    李四正在购买第19张票
    王五正在购买第18张票
    王五正在购买第17张票
    李四正在购买第16张票
    张三正在购买第15张票
    王五正在购买第14张票
    李四正在购买第13张票
    张三正在购买第13张票
    王五正在购买第12张票
    张三正在购买第11张票
    李四正在购买第11张票
    王五正在购买第10张票
    李四正在购买第9张票
    张三正在购买第9张票
    王五正在购买第8张票
    李四正在购买第7张票
    张三正在购买第7张票
    王五正在购买第6张票
    张三正在购买第5张票
    李四正在购买第4张票
    王五正在购买第3张票
    张三正在购买第2张票
    李四正在购买第1张票
    王五正在购买第0张票
    张三正在购买第-1张票
复制代码

You can see three people buy 20 tickets. A thread represents a person .20 tickets shared by the three men. But this program is some problem, some people can buy tickets 0, -1 votes. Also there are two people buy the same ticket.

2. Thread State

A thread is a dynamic process of execution, it also has a process from creation to death.

  1. Newborn state: new
  2. Ready state: runnable
  3. Operating status: running
  4. Blocking state: blocked
  5. Finished: dead

Each state transition diagram as follows:

Ready state way:

  1. start () method
  2. Unblocking
  3. Thread switch is switched thread into the ready state
  4. yield () ---- comity process

Blocking the way into the state:

  1. sleep () method
  2. join () method
  3. wait () method

Enter terminate state:

  1. Normal is finished
  2. destroy () | stop () Obsolete
  3. Manual identification is determined by

1.sleep () --- thread sleeps

effect:

  1. Simulate network delay
  2. The possibility of amplifying the problem

But by sleep () method of the thread goes to sleep and does not release the resources owned by the object, will only make the CPU resources

By sleep () method simulate what countdown

Example 4:

    public class Countdown implements Runnable{
    	public static void main(String[] args) {
    		 new Thread(new Countdown()).start();
    	}
    	@Override
    	public void run() {
    		for(int i=10;i>=0;i--){
    			try {
    				Thread.sleep(1000);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			if(i==0){
    				System.out.println("过年好...");
    				break;
    			}
    			System.out.println(i);
    		}
    	}
    }
复制代码

As a result of the program:

10
9
8
7
6
5
4
3
2
1
过年好...
复制代码

2.yield () --- ethical, courteous thread

When a thread calls yield () method, pause the currently executing thread object, and perform other threads.

Example 5:

    public class YieldDemo implements Runnable{
    	public static void main(String[] args) {
    		new Thread(new YieldDemo(),"A").start();
    		new Thread(new YieldDemo(),"B").start();
    	}
    	@Override
    	public void run() {
    		System.out.println(Thread.currentThread().getName()+"start...");
    		Thread.yield();  //静态方法
    		System.out.println(Thread.currentThread().getName()+"end...");
    	}
    }
复制代码

As a result of the program:

    A:start...
    B:start...
    A:end...
    B:end...
复制代码

3.join () --- consolidated thread, the thread jump the queue

Example 6:

public class JoinDemo {
	public static void main(String[] args) {
		new Thread(new Father()).start();
	}
}
class Father implements Runnable{
	@Override
	public void run() {
		System.out.println("吃饺子没醋...");
		System.out.println("给儿子钱,让儿子去买醋..");
		Thread th=new Thread(new Son());
		th.start();
		try {
			th.join();//合并线程
		} catch (InterruptedException e) {
			e.printStackTrace();
			System.out.println("儿子丢了,赶紧去找儿子..");
		}
		System.out.println("饺子蘸醋~");
	}
}
class Son  implements Runnable{
	@Override
	public void run() {
		System.out.println("接过钱,去买醋...");
		System.out.println("路边有个电玩城,进去玩10s...");
		for(int i=1;i<=10;i++){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(i+"s...");
		}
		System.out.println("赶紧去买醋...");
		System.out.println("把醋递给爸爸...");
	}
}
复制代码

As a result of the program:

吃饺子没醋...
给儿子钱,让儿子去买醋..
接过钱,去买醋...
路边有个电玩城,进去玩10s...
1s...
2s...
3s...
4s...
5s...
6s...
7s...
8s...
9s...
10s...
赶紧去买醋...
把醋递给爸爸...
饺子蘸醋~
复制代码

3. Thread Safety

Written above simulation we see some people buy tickets buy tickets -1, some two people buy the same ticket. This is the case with multiple threads simultaneously operating a resource when it may appear thread safe question.

To deal with this security problem, we can synchronize synchronized control thread safety keyword

Keywords can be synchronized synchronization method, sync blocks.

Synchronization methods can be synchronous static method and member method

The method of sync blocks:

    synchronized(类|this|资源){
         代码
    }
复制代码

Class: Class object class name of a class of a class .class only a Class object

Range synchronization is too large and inefficient.

Synchronous range is too small, not lock.

Use the keyword synchronized lock things should change things, change things not lock.

Rewrite analog tickets:

Example 7:

    public class BuyTikets implements Runnable {
    	@Override
    	public void run() {
    		while (true) {
    			synchronized (Tikets.class) {
    				if (Tikets.tikets <= 0) {
    					break;
    				}
    				try {
    					Thread.sleep(100);
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    				System.out.println(Thread.currentThread().getName() + "正在购买第" + Tikets.tikets-- + "张票");
    			}
    		}
    	}
    	public static void main(String[] args) {
    		BuyTikets td = new BuyTikets();
    		new Thread(td, "张三").start();
    		new Thread(td, "李四").start();
    		new Thread(td, "王五").start();
    	}
    }
    class Tikets {
    	static int tikets = 20;
    }
复制代码

As a result of the program:

    张三正在购买第20张票
    李四正在购买第19张票
    李四正在购买第18张票
    李四正在购买第17张票
    李四正在购买第16张票
    李四正在购买第15张票
    王五正在购买第14张票
    李四正在购买第13张票
    张三正在购买第12张票
    李四正在购买第11张票
    王五正在购买第10张票
    李四正在购买第9张票
    李四正在购买第8张票
    张三正在购买第7张票
    李四正在购买第6张票
    王五正在购买第5张票
    李四正在购买第4张票
    李四正在购买第3张票
    张三正在购买第2张票
    李四正在购买第1张票
复制代码

So you do not buy a ticket situation errors occur.

Guess you like

Origin juejin.im/post/5dbec4376fb9a0206721928d