Why do I need multiple threads?
Simplification of the model, such as some programs are run by a number of relatively independent tasks:
The appearance of graphical interface, the blocking of input and output
Multi-core CPU for better utilization
The need for asynchronous behavior
Java Multi-Threading features:
The entry of the program main itself is a thread
Threads are concurrent, unordered execution
The threads are executed sequentially inside the thread
Share data
Java Multi-Threading risk:
Security risk: Because the order of operation of threads is indeterminate, some programs that run under a single thread can have unexpected results under multithreading.
Performance risk: Server throughput, responsiveness, resource consumption
Java multithreaded APIs:
Java can create threads in two forms: first, implement Runnable interface, second, inherit thread class.
Inheritance thread creation Threading sample code
Copy Code code as follows:
public class ThreadTest extends Thread {
public static void Main (string[] args) {
ThreadTest thread = new ThreadTest ();
Thread.Start ();
for (int i=0; i<10; i++) {
System.out.println ("main:" +i);
}
}
@Override
public void Run () {
for (int i=0; i<10; i++) {
System.out.println ("Thread:" +i);
}
}
}
Implementing runnable Creating Thread code
Copy Code code as follows:
Package Com.openrdp.thread.api;
public class Runnabletest implements Runnable {
public static void Main (string[] args) {
Runnabletest runnable = new Runnabletest ();
Thread thread = new Thread (runnable);
Thread.Start ();
for (int i=0; i<10; i++) {
System.out.println ("main:" +i);
}
}
@Override
public void Run () {
for (int i=0; i<10; i++) {
System.out.println ("Thread:" +i);
}
}
}
Java Thread Pooling Technology
Executors get Exceuctorservice thread pool code
Copy Code code as follows:
Package Com.openrdp.thread.api;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
public class Treadpooltest {
public static void Main (string[] args) {
Executorservice ThreadPool = Executors.newfixedthreadpool (99);
Taskthread thread1 = new Taskthread ("T1");
Threadpool.execute (THREAD1);
Taskthread thread2 = new Taskthread ("T2");
Threadpool.execute (THREAD2);
}
Static Class Taskthread implements Runnable {
String param;
Public taskthread (String param) {
This.param = param;
}
@Override
public void Run () {
}
}
}