Multithreading
What is multi-threading:
Multi-tasking multiple paths simultaneously perform multiple sequential streams multithreaded
The advantages of multi-threading:
Improve efficiency, while performing
Multithreading disadvantages:
Complex
Multithreaded created:
-
Thread class inheritance, override run () method, a method defined in the thread body RUN multithreaded
/** * 线程创建方式 * @author zhuch * */ public class ThreadTest extends Thread{ @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println("犯困"); } } public static void main(String[] args) throws InterruptedException { //创建 ThreadTest t=new ThreadTest(); //开启 t.start(); // TODO Auto-generated method stub for (int i = 0; i < 5; i++) { System.out.println("瞌睡"); Thread.sleep(100); } } }
-
Implement Runnable, override run () method
recommend:
- Avoid the limitations of single inheritance
- Resource sharing
/** * 线程创建方式2 * @author zhuch * */ public class RunnableTest implements Runnable{ @Override public void run() { // TODO Auto-generated method stub for (int i = 0; i < 5; i++) { System.out.println("梦想"); } } public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub Thread t=new Thread(new RunnableTest()); t.start(); for (int i = 0; i < 5; i++) { System.out.println("远方"); Thread.sleep(10); } } }
-
Callable interface to achieve, rewrite method call
advantage:
- You can throw an exception
- Receiving a return value
Disadvantages: trouble
Security Thread:
- Simultaneous operation of multiple threads with a thread may occur only resource problem of insecurity, the need to control security
Genlock:
synchronized
-
Queuing thread to execute the code for the {}
-
Sync block synchronized (locked content) {} synchronization code range
-
Lock content: this class .class resources (member variables)
-
Class .class equivalent to all the contents of this class, the class locked, like all objects are locked
-
The current members of this call object methods, resources equivalent to all the objects are locked, you can only lock resources
-
Resources: member variables, data types must refer to objects if the custom
-
Lock range: {} -> range of the code
-
note:
- The lock is too large, inefficient
- Lock range is too small, not lock
- Lock same content
/** * 多线程打印12A23B45C67D...直到字母打印完结束 * @author zhuch * */ public class Test { public static void main(String[] args) { //创建对象 PrintTest pr=new PrintTest(); //开启线程 new Thread(new Number(pr)).start(); new Thread(new CharTest(pr)).start(); } } //行为 class PrintTest{ //成员变量 boolean flag=false; int num=1; char num1='A'; //打印数字(同步块) public synchronized void number() { if(flag==true) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i=0;i<2;i++) { if(num==53) { return; } System.out.print(num++); } flag=true; this.notify(); } } //打印字母(同步块) public synchronized void charTest() { if(flag==false) { try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.print((char)(num1++)); flag=false; this.notify(); } } } //数字类实现Runnable接口重写run方法 class Number implements Runnable{ PrintTest pr=null; public Number(PrintTest pr) { super(); this.pr = pr; } @Override public void run() { // TODO Auto-generated method stub while(true) { pr.number(); } } } //字母类实现Runnable接口重写run方法 class CharTest implements Runnable{ PrintTest pr=null; public CharTest(PrintTest pr) { super(); this.pr = pr; } @Override public void run() { // TODO Auto-generated method stub while(true) { pr.charTest(); } } }
public class SynchronizedTest implements Runnable{ Ticket ticket=new Ticket(); public static void main(String[] args) { // TODO Auto-generated method stub SynchronizedTest syn=new SynchronizedTest(); new Thread(syn,"A").start(); new Thread(syn,"B").start(); new Thread(syn,"C").start(); } @Override public void run() { // TODO Auto-generated method stub while(true) { synchronized(this) { if(ticket.num<=0) { break; } try { Thread.sleep(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"正在购买第"+ticket.num-- +"张票"); } } } } class Ticket{ int num=100; }
Thread Status:
-
Newborn state: new to create a thread when
-
Ready state: start (), thread into the ready queue, waiting for the cpu scheduling
-
Operating status: cpu time slice allocated to the calling thread, the thread will run
-
Blocking state: sleep () ...
-
End state: the end of the thread
-
As soon as a thread to a blocking state, after unblocking, will not be restored immediately to run, it will return to the ready state, waiting for the cpu scheduling again
-
Once in the state to terminate a thread, never recover
-
How a thread into the ready state:
- 1.start()
- 2. unblocking
- 3. Thread switching is switched thread will be ready to state
- 4.yield () comity thread
-
Blocking the way into the state:
-
1.sleep
-
2.wait
-
3.join
-
-
How to control a thread termination:
- 1.stop ... not recommended
- 2. Analyzing represents
- 3. Normal execution ends
-
sleep (): thread to sleep
- 1) simulate latency
- 2) the possibility Magnification
- Let the cpu resources, will not let a lock object (to ensure that resources go to bed), specify how many milliseconds rest
public class StateTest implements Runnable{
public static void main(String[] args) {
// TODO Auto-generated method stub
StateTest sta=new StateTest();
new Thread(sta,"A").start();
new Thread(sta,"B").start();
}
@Override
public void run() {
// TODO Auto-generated method stub
Thread t=new Thread(()-> {
for (int i = 0; i < 20; i++) {
System.out.println("插队");
try {
Thread.sleep(5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
try {
t.join();//方法插队
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"开始执行");
Thread.yield();//礼让线程
System.out.println(Thread.currentThread().getName()+"结束执行");
}
}
Thread in getState () to obtain the status of a thread
Thread priority:
-
提高先执行的概率
- getPriority () returns the priority of the thread
- setPriority (int newPriority) change the priority of this thread
- 10 1 ~ 10 1 Min 5 default maximum
public class StateDemo02 {
public static void main(String[] args) {
Thread th=new Thread(()->{
for(int i=0;i<=10;i++){
if(i==5){
try {
Thread.sleep(5);
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
th.setPriority(10);
System.out.println(th.getPriority());
System.out.println("th线程状态"+th.getState());
th.start();
while(true){
Thread.State state=th.getState();
System.out.println(state);
if(state ==Thread.State.TERMINATED){
break;
}
try {
Thread.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}