Java基础学习笔记之多线程

用多线程只有一个目的,那就是更好的利用cpu的资源,因为所有的多线程代码都可以用单线程来实现。说这个话其实只有一半对,因为反应“多角色”的程序代码,最起码每个角色要给他一个线程吧,否则连实际场景都无法模拟,当然也没法说能用单线程来实现:比如最常见的“生产者,消费者模型”。

创建新线程

1.继承Thread

1
2
3
4
5
6
class Comet extends Thread {
public void run() {
System.out.println("Orbiting");
orbit();
}
}

2.实现Runnable接口

1
2
3
4
5
6
7
8
9
class Asteroid implements Runnable {
public void run() {
System.out.println("Orbiting");
orbit();
}
}

Asteroid maja = new Asteroid();
Thread majaThread = new Thread(maja);

Thread的状态

线程状态 说明
NEW A thread that is created but not started
RUNNABLE A thread that is available to run
BLOCKED An “alive” thread that is blocked waiting for a monitor lock
WAITING An “alive” thread that calls its own wait() or join() while waiting on another thread
TIMED_WAITING An “alive” thread that is waiting on another thread for a specified period of time; sleeping
TERMINATED A thread that has completed

Thread普通方法

方法 说明
getPriority() Returns the thread’s priority
getState() Returns the thread’s state
interrupt() Interrupts the thread
isAlive() Returns the thread’s alive status
isInterrupted() Checks for interruption of the thread
join() Causes the thread to wait for another thread to complete
setPriority(int) Sets the thread’s priority
start() Places the thread into a runnable state

Thread重载Object的方法

方法 说明
notify() Tells a thread to wake up and run
notifyAll() Tells all threads that are waiting on a thread or resource to wake up, and then the scheduler will select one of the threads to run
wait() Pauses a thread in a wait state until another thread calls notify() or notifyAll()

Thread静态方法

方法 说明
activeCount() Returns number of threads in the current thread’s group
currentThread() Returns reference to the currently running thread
interrupted() Checks for interruption of the currently running thread
sleep(long) Blocks the currently running thread for parameter number of milliseconds
yield() Pauses the current thread to allow other threads to run

线程的同步

线程同步采用关键字synchronized,意味着对代码块或者方法加锁,使用场景有:

  • 1.对实例t使用同步锁

    1
    2
    3
    synchronized (t) {
    // Block body
    }
  • 2.对实例this使用同步锁

    1
    2
    3
    synchronized (this) {
    // Block body
    }
  • 3.对成员方法raise()使用同步锁,两种方法等效

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // Equivalent code segment 1
    synchronized void raise() {
    // Method Body
    }

    // Equivalent code segment 2
    void raise() {
    synchronized (this) {
    // Method body
    }
    }
  • 4.对静态方法calibrate()使用同步锁

    1
    2
    3
    4
    5
    class Telescope {
    synchronized static void calibrate() {
    // Method body
    }
    }

多线程工具包

java对多线程提供了工具包java.util.concurrent

线程池 Executors

Executors提供了工厂方法来创建线程池

方法 说明
newCachedThreadPool() Creates an unbounded thread pool that automatically reuses threads
newFixedThreadPool(int nThreads) Creates a fixed-size thread pool that automatically reuses threads off a shared unbounded queue
newScheduledThreadPool(int corePoolSize) Creates a thread pool that can have commands scheduled to run periodically or on a specified delay
newSingleThreadExecutor() Creates a single-threaded executor that operates off an unbounded queue
newSingleThreadScheduledExecutor() Creates a single-threaded executor that can have commands scheduled to run periodically or by a specified delay

使用实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Create tasks
// (from 'class RTask implements Runnable')
RTask t1 = new RTask("thread1");
RTask t2 = new RTask("thread2");

// Create thread manager
ExecutorService threadExecutor = Executors.newFixedThreadPool(2);

// Make threads runnable
threadExecutor.execute(t1);
threadExecutor.execute(t2);

// Shutdown threads
threadExecutor.shutdown();

线程安全集合类

尽管集合类可以被同步,但最好使用java提供的线程安全集合类。

集合类 对应的线程安全集合类
HashMap ConcurrentHashMap
TreeMap ConcurrentSkipListMap
TreeSet ConcurrentSkipListSet
Map subtypes ConcurrentMap
List subtypes CopyOnWriteArrayList
Set subtypes CopyOnWriteArraySet
PriorityQueue PriorityBlockingQueue
Deque BlockingDeque
Queue BlockingQueue

同步器/信号量

类型 说明
Semaphore Maintains a set of permits
CountDownLatch Implements waits against sets of operations being performed
CyclicBarrer Implements waits against common barrier points
Exchanger Implements a synchronization point where threads can exchange elements

时间单位常量TimeUnit

Constants Unit def. Unit (sec) Abbreviation
NANOSECONDS 1/1000 μs .000000001 ns
MICROSECONDS 1/1000 ms .000001 μs
MILLISECONDS 1/1000 sec .001 ms
SECONDS sec 1 sec
MINUTES 60 sec 60 min
HOURS 60 min 3600 hr
DAYS 24 hr 86400 d

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器