1, the process differs threads:
Open the operating system a notepad, is to start a program, representing the operating system allocates a block of memory to the program process, a process has at least one thread, the thread is the smallest execution unit can be shared data process, the overhead is relatively small;
Open a program will start a process, there is a carry at least one thread, process data can be shared between multiple threads;
2, concurrent with the difference in parallel:
Parallel: referring to the same time a plurality of instructions for execution on a processor; are performed simultaneously;
Concurrency: refers to a time, only one command is executed, but will rotate faster execution of multiple instructions
Our own open operating system, the computer open music, open Notepad and the operating system CPU is rotated in the implementation process of the implementation of each command, only the CPU processing speed faster, we do not feel;
3, create multiple threads:
Method One: Thread class inheritance
public class ThreadTest extends Thread {
public ThreadTest(String name) {
super(name);
}
@Override
public void run() {
for (int i=0;i<10;i++) {
System.out.println(currentThread().getName()+" is running"+i);
}
}
public static void main(String[] args) {
//1------自定义类继承Thread类
ThreadTest newThreadTest=new ThreadTest("new Thread");
//2------启动线程
newThreadTest.start();
for (int i=0;i<10;i++) {
System.out.println(currentThread().getName()+" is running"+i);
}
}
}
main is running0
main is running1
main is running2
main is running3
main is running4
main is running5
main is running6
main is running7
main is running8
main is running9
new Thread is running0
new Thread is running1
new Thread is running2
new Thread is running3
new Thread is running4
new Thread is running5
new Thread is running6
new Thread is running7
new Thread is running8
new Thread is running9
Method two: implement Runnable
public class InterfaceThead implements Runnable{
@Override
public void run() {
for (int i=0;i<10;i++) {
System.out.println("my thread "+" is running"+i);
}
}
public static void main(String[] args) {
//1----定义一个类实现Runnable接口并重写其中的run方法
InterfaceThead threadInterfaceThead=new InterfaceThead();
//2----将runnable作为Thread 的构造参数传入target
Thread tesThread=new Thread(threadInterfaceThead);
//3-----启动线程
tesThread.start();
}
}
my thread is running0
my thread is running1
my thread is running2
my thread is running3
my thread is running4
my thread is running5
my thread is running6
my thread is running7
my thread is running8
my thread is running9
Method three:
public class CallableThread implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("开始调用新的线程!");
return "有返回值的线程!";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
//1-----FutureTask包装callable对象,其中callable要重写call方法
FutureTask task=new FutureTask<String>(new CallableThread());
//2-----将futureTask作为new Thread(target,name)
Thread thread=new Thread(task, "callableThread");
//3-----启动线程
thread.start();
//4-----接收返回的值
if(task.get() != null) {
System.out.println(task.get());
}
}
}
Conclusion : Either way, calls the method of the Thread is run, if a method is not applicable, do not cover the run method of the Thread, use Method Two and Three methods will pass a target of Runable or Callable run call methods: Check out Thread run method source source code:
@Override
public void run() {
if (target != null) {
target.run();
}
}
4, the thread cycle:
This picture from the network
Thread five states:
New State : new method of using the new Thread () system will allocate memory for the thread, in the ready state;
Ready state : runnable start using the method of Thread is a thread in the ready state waits for the call of the JVM;
Operating status : run JVM start calling the thread
Blocking state : blocked so that other thread being executed to obtain access to resources, for the time being will be the executing thread blocked, usually preemptive scheduling strategy used, you can use sleep or yield for the time being the initiative for the current resource;
1. Wait for blocking: execution wait thread running state () method, so that the thread is blocked waiting to enter the state; wait will release the lock held
2. synchronous blocking - thread synchronization lock failure in obtaining synchronized (because the lock was occupied by another thread), it will enter synchronous blocking state;
3. Other blocked - by sleep () or join the calling thread () or issued I / O request, the thread into the blocked state. When sleep () timeout, the Join () or a timeout wait for a thread to terminate, or I / O processing is completed, the thread into the ready state again.
Death state : Thread execution is over or due to abnormal exit the run () method, the thread end of the life cycle
5, the threads of control:
Source: HTTPS: //www.jianshu.com/p/3c85daeba1a5
SLEEP method
/**
* SleepTest 继承线程Thread类,每1秒打印一次时间;
* 主线程sleep 9秒,
* interrupt子线程
*
*
*/
public class SleepTest extends Thread {
@Override
public void run() {
while(true) {
System.out.println("now time is "+new Date());
try {
sleep(1000);
} catch (InterruptedException e) {
System.out.println(currentThread().getName()+"is be interruped!");
return ;
}
}
}
public static void main(String[] args) {
SleepTest test=new SleepTest();
test.start();
try {
Thread.sleep(9000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(currentThread().getName()+" is running!");
test.interrupt();
}
}
now time is Thu Sep 12 15:43:34 CST 2019
now time is Thu Sep 12 15:43:35 CST 2019
now time is Thu Sep 12 15:43:36 CST 2019
now time is Thu Sep 12 15:43:37 CST 2019
now time is Thu Sep 12 15:43:38 CST 2019
now time is Thu Sep 12 15:43:39 CST 2019
now time is Thu Sep 12 15:43:40 CST 2019
now time is Thu Sep 12 15:43:41 CST 2019
now time is Thu Sep 12 15:43:42 CST 2019
main is running!
Thread-0is be interruped!
yield method
/**
* yield方法调用后,线程会暂时处于就绪状态等待JVM的调用,可能就会立即被调用
*
*
*/
public class YieldTest extends Thread{
@Override
public void run() {
for(int i=0;i<20;i++) {
System.out.println(currentThread().getName()+" is running "+i);
if(i%2==0) {
Thread.yield();
}
}
}
public static void main(String[] args) {
YieldTest test1=new YieldTest();
YieldTest test2=new YieldTest();
test1.start();
test2.start();
}
}
Thread-0 is running 10
Thread-1 is running 8
Thread-0 is running 11
Thread-0 is running 12
Thread-1 is running 9
Thread-1 is running 10
Thread-0 is running 13
Thread-0 is running 14
Thread-1 is running 11
Thread-1 is running 12
Thread-0 is running 15
Thread-0 is running 16
Thread-0 is running 17
Thread-0 is running 18
Thread-1 is running 13
Thread-1 is running 14
Thread-0 is running 19
Thread-1 is running 15
Thread-1 is running 16
Thread-1 is running 17
Thread-1 is running 18
Thread-1 is running 19
join method
/*
* join就是等待线程执行完毕后才能执行另一个线程
*/
public class JoinTest extends Thread {
@Override
public void run() {
for(int i=0;i<10;i++) {
System.out.println(currentThread().getName()+" is running "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JoinTest test=new JoinTest();
test.start();
try {
test.join(9000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("i am the main thread");
}
}
Thread-0 is running 0
Thread-0 is running 1
Thread-0 is running 2
Thread-0 is running 3
Thread-0 is running 4
Thread-0 is running 5
Thread-0 is running 6
Thread-0 is running 7
Thread-0 is running 8
i am the main thread
Thread-0 is running 9
wait method
/**
*
* 模拟一个存钱取钱的过程:
* 要求必须先将钱存进去才能取出
*
*/
public class WaitTest {
//定义一个属性
private int i;
public static void main(String[] args) {
WaitTest tetsTest=new WaitTest();
PutInto into=new PutInto(tetsTest);
PutOut out=new PutOut(tetsTest);
into.start();
out.start();
}
public synchronized void putIntoMoney(){
//如果现在钱不是0,就要先取出来,等待其他的线程取钱,释放锁
if (i!=0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//值为0时需要加把钱放进去了
i++;
System.out.println("我把钱放进去了!");
//通知其他的可以进行取钱了
notify();
}
public synchronized void putOutMoney() {
//值为0需要先将钱放进去,等待其他线程放钱进去,先释放锁
if(i==0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//值为1时需要加把钱放取出了
i--;
System.out.println("我把钱取出来了!");
//通知其他的可以进行放钱了
notify();
}
}
//----放钱的线程--------
class PutInto extends Thread{
//模拟人
private WaitTest per;
public PutInto(WaitTest per){
this.per=per;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
per.putIntoMoney();
}
}
}
//------取钱的线程-------
class PutOut extends Thread{
//模拟人
private WaitTest per;
public PutOut(WaitTest per){
this.per=per;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
per.putOutMoney();
}
}
}
我把钱取出来了!
我把钱放进去了!
我把钱取出来了!
我把钱放进去了!
我把钱取出来了!
。。。。。。
Application summarize it:
join method:
waiting for a thread to perform after the completion of the next thread, the thread will cause obstruction, such as you line up to withdraw money only on a customer service is finished before it's your turn;
yield method:
Let the executing thread is blocked, the opportunity may be performed immediately after thread calls this method, it may make it a higher priority than the thread;
Methods sleep:
and as yield will not release the lock, the thread is blocked, sleep (time) time-out will automatically wake up
wait method
is synchronized in a sync block in
the method of the Object is wait, the call will release the lock, a plurality of objects if the objects of this operation will obtain the lock for this object;
may be used herein synchronization monitor wake notify a thread on;
nitifyall wake up all the threads in this synchronization monitor;
6, start the thread pool policy
1, when the thread pool just created, there is no thread, the task queue is passed in as a parameter, however, even if there is no task queue, the thread pool will not execute them immediately;
2, when calling execute () method to add a task, the thread pool will make the following judgment:
Source network
The next section we explain the lower thread and the thread pool safety issues