Java
Java
-
CPU
- :
new Thread start()
- :
start()JVM
- :
CPU run()
- :
sleepsuspend
wait()
synchronized ()
sleep() join() I/O sleep() join() I/O
- :
Java
Java 1 Thread.MIN_PRIORITY - 10 Thread.MAX_PRIORITY
NORM_PRIORITY5
Java
- Runnable
- Thread
- Callable Future
Runnable
Runnable
Runnable run()
public void run()
run()
Runnable
Thread
Thread(Runnable threadOb,String threadName);
threadOb Runnable threadName
start()
void start();
class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
//
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting.
Thread
Thread
run() start()
Runnable
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
//
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}
Creating Thread-1 Starting Thread-1 Creating Thread-2 Starting Thread-2 Running Thread-1 Thread: Thread-1, 4 Running Thread-2 Thread: Thread-2, 4 Thread: Thread-1, 3 Thread: Thread-2, 3 Thread: Thread-1, 2 Thread: Thread-2, 2 Thread: Thread-1, 1 Thread: Thread-2, 1 Thread Thread-1 exiting. Thread Thread-2 exiting.
Thread
Thread
| 1 |
public void start() Java run |
| 2 |
public void run() Runnable Runnable run |
| 3 |
public final void setName(String name) name |
| 4 |
public final void setPriority(int priority) |
| 5 |
public final void setDaemon(boolean on) |
| 6 |
public final void join(long millisec) millis |
| 7 |
public void interrupt() |
| 8 |
public final boolean isAlive() |
Thread Thread
| 1 |
public static void yield() |
| 2 |
public static void sleep(long millisec) |
| 3 |
public static boolean holdsLock(Object x) true |
| 4 |
public static Thread currentThread() |
| 5 |
public static void dumpStack() |
ThreadClassDemo Thread
DisplayMessage.java
// : DisplayMessage.java
// Runnable
public class DisplayMessage implements Runnable {
private String message;
public DisplayMessage(String message) {
this.message = message;
}
public void run() {
while(true) {
System.out.println(message);
}
}
}
GuessANumber.java
// : GuessANumber.java
// Thread
public class GuessANumber extends Thread {
private int number;
public GuessANumber(int number) {
this.number = number;
}
public void run() {
int counter = 0;
int guess = 0;
do {
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName() + " guesses " + guess);
counter++;
} while(guess != number);
System.out.println("** Correct!" + this.getName() + "in" + counter + "guesses.**");
}
}
ThreadClassDemo.java
// : ThreadClassDemo.java
public class ThreadClassDemo {
public static void main(String [] args) {
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye = new DisplayMessage("Goodbye");
Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try {
thread3.join();
}catch(InterruptedException e) {
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}
Starting hello thread... Starting goodbye thread... Hello Hello Hello Hello Hello Hello Goodbye Goodbye Goodbye Goodbye Goodbye .......
Callable Future
1. Callable call() call()
2. Callable FutureTask Callable FutureTask Callable call()
3. FutureTask Thread target
4. FutureTask get()
public class CallableThreadTest implements Callable<Integer> {
public static void main(String[] args)
{
CallableThreadTest ctt = new CallableThreadTest();
FutureTask<Integer> ft = new FutureTask<>(ctt);
for(int i = 0;i < 100;i++)
{
System.out.println(Thread.currentThread().getName()+" i"+i);
if(i==20)
{
new Thread(ft,"").start();
}
}
try
{
System.out.println(""+ft.get());
} catch (InterruptedException e)
{
e.printStackTrace();
} catch (ExecutionException e)
{
e.printStackTrace();
}
}
@Override
public Integer call() throws Exception
{
int i = 0;
for(;i<100;i++)
{
System.out.println(Thread.currentThread().getName()+" "+i);
}
return i;
}
}
1. RunnableCallable Runnable Callable
2. Thread Thread.currentThread() this
CPU
dg5uw
159***[email protected]
1
2
javajvm
3
4
1Runnable
Test.java
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String[] args) { // 55 ExecutorService service = Executors.newFixedThreadPool(5); //Runnable TaskRunnable task = new TaskRunnable(); // service.submit(task); System.out.println("----------------------"); // service.submit(task); // service.shutdown(); } }TaskRunnable.java
public class TaskRunnable implements Runnable{ @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println(""+i); } } }2Callable
CallableRunnablecall()call
ExecutorService
<T> Future<T> submit(Callable<T> task) call()
Future
Test.java
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test{ public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(3); TaskCallable c = new TaskCallable(); //run service.submit(c); // service.submit(c); // service.shutdown(); } }TaskCallable.java
import java.util.concurrent.Callable; public class TaskCallable implements Callable<Object>{ @Override public Object call() throws Exception { for (int i = 0; i < 1000; i++) { System.out.println(""+i); } return null; } }dg5uw
159***[email protected]
dg5uw
159***[email protected]
Callable
Future
get() Future
ThreadPoolDemo.java
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadPoolDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { // ExecutorService threadPool = Executors.newFixedThreadPool(2); //Callable //MyCallable c = new MyCallable(); MyCallable c = new MyCallable(100, 200); MyCallable c2 = new MyCallable(10, 20); //Callablecall(), //<Integer> Future<Integer> submit(Callable<Integer> task) // Future Future<Integer> result = threadPool.submit(c); // Future get Integer sum = result.get(); System.out.println("sum=" + sum); // result = threadPool.submit(c2); sum = result.get(); System.out.println("sum=" + sum); //() } }MyCallable.java
import java.util.concurrent.Callable; public class MyCallable implements Callable<Integer> { // int x = 5; int y = 3; // public MyCallable(){ } public MyCallable(int x, int y){ this.x = x; this.y = y; } @Override public Integer call() throws Exception { return x+y; } }dg5uw
159***[email protected]
0space
960***[email protected]
CPU
1
2 ()()()
3
4
0space
960***[email protected]
553***[email protected]
Java Thread run() start()
Java java.lang.Thread VM Thread Thread run() run() Thread start()
Java
cpustart CPU run() CPU run()
start() CPU JVM Thread run() start run run start
CPU
public class Test { public static void main(String[] args) { Runner1 runner1 = new Runner1(); Runner2 runner2 = new Runner2(); // Thread(Runnable target) Thread Thread thread1 = new Thread(runner1); Thread thread2 = new Thread(runner2); // thread1.start(); // thread2.start(); thread1.run(); thread2.run(); } } class Runner1 implements Runnable { // Runnablejdk public void run() { for (int i = 0; i < 100; i++) { System.out.println("Runner1——————————" + i); } } } class Runner2 implements Runnable { // Runnablejdk public void run() { for (int i = 0; i < 100; i++) { System.out.println("Runner2==========" + i); } } }553***[email protected]
HelloWorld
zhy***@qq.com
[716271-20170320112245721-1831918220.jpg]
5 :1. (New): Thread thread = new Thread()
2. (Runnable): start()thread.start()CPU
3. (Running): CPU
4. (Blocked): CPU
5. (Dead): run()
HelloWorld
zhy***@qq.com
cz
109***[email protected]
run synchronized {}
Public synchronized {}Lock
Lock finally
Lock synchronized JDK1.5
Lock :
Lock :
:
public class RunnableImpl implements Runnable{ // private int ticket = 100; //1.ReentrantLock Lock l = new ReentrantLock(); //: @Override public void run() { //, while(true){ //2.,Locklock l.lock(); //0 if(ticket>0){ //,10 try { // Thread.sleep(10); // ticket-- System.out.println(Thread.currentThread().getName()+""+ticket+"!"); ticket--; } catch (InterruptedException e) { // e.printStackTrace(); }finally { //,() //3.,Lockunlock l.unlock();//,,, } } } } }cz
109***[email protected]
vvv
201***[email protected]
CompletableFuture
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; public class CompletableFutureDemo { public static void main(String[] args) throws InterruptedException { long l = System.currentTimeMillis(); CompletableFuture<Integer> completableFuture = CompletableFuture.supplyAsync(() -> { System.out.println("..."); timeConsumingOperation(); return 100; }); completableFuture.whenComplete((result, e) -> { System.out.println("" + result); }); System.out.println(":" + (System.currentTimeMillis() - l) + " ms"); new CountDownLatch(1).await(); } static void timeConsumingOperation() { try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } } }java.util.concurrent.CompletableFuture CompletableFuture 50 java
vvv
201***[email protected]
139***[email protected]
javaObject
notify() wait()
notifyAll()
wait()WAITING
wait()
wait(long) n
wait(long, int)
139***[email protected]