文章目录
线程、进程、并行、并发概念
并发:并发是指在同一时间段内有多个事情发生,但是每一时刻只能处理一个事情。
并行:并行是指在同一时间段内有多个事情,同一时刻可以处理多个事情。
进程:进程是指在内存中运行的应用程序,每个进程都有自己独立的空间内存。
线程:线程是进程中的一个执行单元,一个进程中至少有一个线程。
多线程三种实现方式
1、继承Thread
1)创建一个Thread的子类MyThread,重写run()方法。
2)new一个MyThread对象myThread,
3)通过myThread.start()启动线程
代码:
class MyThread extends Thread {
@Override
public void run() {
//线程执行体
System.out.println("线程体执行");
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
2、Runnable
1)自定义一个Runnable的实现类MyThread,重写run()方法,
2)new一个MyThread对象myThread。
3)new一个Thread对象thread将myThread传入构造器。
4)通过thread.start启动线程。
代码:
class MyThread implements Runnable {
@Override
public void run() {
//线程执行体
System.out.println("线程执行体执行");
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread MyThread = new MyThread();
Thread thread = new Thread(MyThread);
thread.start();
}
}
3、Callable接口
一般情况下,使用Runnable接口和Thread实现的线程我们都无返回结果,但是如果有些场合需要线程返回结果,就要使用Callable、Future。Callable只能在ExecutorService的线程池中跑。
示例:
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(10);
MyCallable myCallable1 = new MyCallable();
MyCallable myCallable2 = new MyCallable();
Future submit = executorService.submit(myCallable1);
Future submit1 = executorService.submit(myCallable2);
System.out.println(submit.get());
}
}
class MyCallable implements Callable{
@Override
public Integer call() throws Exception {
int sum = 0;
Integer nextInt = new Random().nextInt();
for (int i = 0; i < nextInt; i++) {
sum += i;
}
return sum;
}
}
多线程的五种状态
1、新建状态:就是new的过程。
2、就绪状态:线程对象创建后,其他线程调用该对象的start()方法后,该线程就进入到就绪状态。
3、运行状态:就绪状态的线程获取到了cup,进入运行状态,执行程序代码。
4、阻塞状态:当一个线程在运行过程中因为某些原因,让出了cpu执行权,此时该线程处于阻塞状态。
5、死亡状态:线程执行完毕正常退出或遇到错误异常退出。
常用方法
Thread.sleep(long millis) 线程睡眠
让当前线程进入阻塞状态,millis是设置睡眠毫秒值,到达设定时间后会转为就绪状态,sleep不释放锁。
wait() 线程等待
释放锁,让当前线程进入等待状态,待其他线程调用此线程对象的notify方法或notifyAll()方法时回到就绪状态。
notify() notifyAll() 线程唤醒
唤醒之前wait()的线程。
join() 合并线程
在当前线程中调用另一个线程,当前线程进入阻塞状态,直至被调用线程执行完再有阻塞状态转为就绪状态。
yield() 线程让步
放弃当前拥有的cup资源,让当前运行线程切换到可运行状态,以允许拥有相同优先级的线程之间能轮转执行。
线程安全问题
当两个或两个以上的线程需要对同一数进行读写操作时,会出现线程安全问题。
解决办法(同步存储)
1)同步代码块
语法:
synchronized(临界资源对象){ //对临界资源对象加锁
//代码(原⼦操作)此代码块中的代码,在同一时间只能有一个线程执行。
}
class TicketThread implements Runnable {
private Integer ticket = 100; //有一百张票
@Override
public void run() {
synchronized (this.getClass()) {
while(ticket > 0) {
System.out.println(Thread.currentThread().getName()+"卖出第" + ticket-- + "张票");
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
TicketThread ticketThread = new TicketThread();
new Thread(ticketThread,"窗口1").start();
new Thread(ticketThread,"窗口2").start();
new Thread(ticketThread,"窗口3").start();
}
}
2)同步方法
同步方法就是用synchronized 修饰的方法,
它会有一个隐含锁对象
普通方法的隐含锁对象是this
如果是静态同步方法,隐含锁对象是类名.class,如果此代码块执行,就没有其他线程能调用此类中其他的同步静态方法
class TicketThread implements Runnable {
private static Integer ticket = 100; //有一百张票
@Override
public void run() {
ticket();
}
public static synchronized void ticket(){
while(ticket > 0) {
System.out.println(Thread.currentThread().getName()+"卖出第" + ticket-- + "张票");
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
TicketThread ticketThread = new TicketThread();
new Thread(ticketThread,"窗口1").start();
new Thread(ticketThread,"窗口2").start();
new Thread(ticketThread,"窗口3").start();
}
}
3)Lock(jdk1.5加入)
方法名 | 描述 |
---|---|
void lock() | 获取锁,如锁被占用,则等待 |
boolean tryLock() | 尝试获取锁(成功返回true,失败返回false) |
void unlock() | 释放锁 |
void await() | 将该线程放到条件的等待集中 |
void signalAll() | 解除该条件的等待集中的所有线程的阻塞状态 |
void signal() | 从该条件的等待集中随机的选择一个线程,解除其阻塞状态 |
注意:unlock()要写在finally里面,
class MyArrayList {
private Lock lock = new ReentrantLock();
private String[] str = {"a","b","","",""};
private Integer count = 2;
public void add(String s) {
lock.lock();
try{
str[count] = s;
try {
Thread.sleep(200); //模拟线程安全问题
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
}finally {
lock.unlock();
}
}
public String[] getAll() {
return str;
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyArrayList thread = new MyArrayList();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
thread.add("he");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
thread.add("hell");
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
String[] all = thread.getAll();
for (String s : all) {
System.out.println(s);
}
}
}
线程池
java.util.concurrent.Executor是线程池的顶级接口,但是严格意义上将,Executor并不是一个线程池,而是一个执行线程的工具,真正的线程池接口是java.util.concurrent.ExecutorService。
方法 | 描述 |
---|---|
newFixedThreadPool | 创建一个固定长度的线程池 |
newCachedThreadPoll | 创建一个可缓存的线程池,当需求增加时线程数量也会增加。 |
newSingleThreadPool | 创建一个单线程的线程池 |
newScheduledThreadPool | 创建一个固定长度的线程池,而且以延迟或定时方式来执行 |
练习题
- 创建两个线程,让它们依次打印ABABAB共打印十次。
class MyThread implements Runnable{
private String name;
private Integer count = 10;
public MyThread(String name) {
this.name = name;
}
@Override
public void run() {
while(count-- > 0) {
synchronized (MyThread.class){
System.out.println(Thread.currentThread().getName() + name);
MyThread.class.notifyAll();
try {
MyThread.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
new Thread(new MyThread("A")).start();
new Thread(new MyThread("B")).start();
}
}
- 启动三个线程打印递增的数字,线程1先打印1,2,3,4,5,然后线程2打印6,7,8,9,10,线程3打印11,12,13,14,15一直打印到75;
方式一:
class MyThread implements Runnable{
private static Integer count = 1;
private Integer cid; //线程标记位
private Integer sid; //当前应当运行的线程
public MyThread(Integer cid) {
this.cid = cid;
}
@Override
public void run() {
while(count <=75) {
synchronized (MyThread.class) {
sid = (count/5)%3+1;
if(sid == cid) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() +"--"+ count++);
}
MyThread.class.notifyAll();
}else{
try {
MyThread.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
new Thread(new MyThread(1)).start();
new Thread(new MyThread(2)).start();
new Thread(new MyThread(3)).start();
}
}
方式二:
class MyThread implements Runnable{
public MyThread(Object prev, Object self) {
this.prev = prev;
this.self = self;
}
private Object prev;
private Object self;
private static Integer count = 1;
@Override
public void run() {
synchronized (prev){
synchronized (self){
while(count <= 75) {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + count++);
}
self.notify();
}
if(count >= 75) {
try {
prev.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Object A = new Object();
Object B = new Object();
Object C = new Object();
new Thread(new MyThread(C,A),"线程一").start();
//Thread.sleep(20);
new Thread(new MyThread(A,B),"线程二").start();
//Thread.sleep(20);
new Thread(new MyThread(B,C),"线程三").start();
//Thread.sleep(20);
}
}
- 创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D
class PrintNum implements Runnable{
public PrintNum(Object obj) {
this.obj = obj;
}
private Object obj;
private Integer count = 1;
@Override
public void run() {
synchronized (obj) {
while(count <= 52) {
if(count>1 && count%2==1) {
System.out.print(" ");
}
System.out.print(count++);
if(count%2==1) {
obj.notify();
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class PrintChar implements Runnable{
public PrintChar(Object obj) {
this.obj = obj;
}
private Object obj;
@Override
public void run() {
synchronized (obj) {
for (char i = 'A'; i <= 'Z'; i++) {
System.out.print(i);
obj.notify();
if(i < 'Z') {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Object obj = new Object();
new Thread(new PrintNum(obj)).start();
new Thread(new PrintChar(obj)).start();
}
}