Java从1.8以后引入了函数式编程,这是很大的一个改进。函数式编程的优点在提高编码的效率,增强代码的可读性。本文历时两个多月一点点写出来,即作为心得,亦作为交流。
以上的接口必须是一个,java8出现了一个新的注解
package java.lang.Thread,是jdk1.0就提供了。
public synchronized void start() {
/**
* This method is not invoked for the main method thread or "system"
* group threads created/set up by the VM. Any new functionality added
* to this method in the future may have to also be added to the VM.
*
* A zero status value corresponds to state "NEW".
*/
//有一个异常抛出,但是没有强制要求处理,因为该异常是RuntimeException
if (threadStatus != 0)
throw new IllegalThreadStateException();
/* Notify the group that this thread is about to be started
* so that it can be added to the group's list of threads
* and the group's unstarted count can be decremented. */
group.add(this);
boolean started = false;
try {
start0();
started = true;
} finally {
try {
if (!started) {
group.threadStartFailed(this);
}
} catch (Throwable ignore) {
/* do nothing. If start0 threw a Throwable then
it will be passed up the call stack */
}
}
}
private native void start0();
public class Thread implements Runnable
它是在这个包下:import java.util.concurrent.*;
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
Thread(Runnable target, AccessControlContext acc) {
init(null, target, "Thread-" + nextThreadNum(), 0, acc, false);
}
public Thread(ThreadGroup group, Runnable target) {
init(group, target, "Thread-" + nextThreadNum(), 0);
}
public Thread(String name) {
init(null, null, name, 0);
}
public Thread(ThreadGroup group, String name) {
init(group, null, name, 0);
}
不详细介绍了
进程分析
经过分析可以发现,都在看各个线程的概念,咱们程序的核心问题,所有的线程都是在进程里面创建的,那进程在哪里呢?答案其实很简单,每当java命令运行一个类的时候就会在操作系统的内部为其分配一个进程,而现在所有的程序执行的时候都是基于线程的方式运行的,其中会由JVM帮助用户手工创建一个主线程(main),而后再由主线程创建若干个线程。
正常情况下我们是多个线程在竞争去抢夺,但是有特殊情况下,某个线程会强制抢夺。
public class MyThread {
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();
Thread joinThread = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
if (i > 10) {
try {
Thread.sleep(1000);
//只要满足i>10那就要把所有的资源交给主线程处理
mainThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "子线程");
}
},"线程A");
joinThread.start();
for (int i = 0; i < 1000; i++) {
Thread.sleep(1000);
System.out.println("当前主线程" + mainThread);
}
}
}
public class MyThread {
public static void main(String[] args) throws InterruptedException {
Thread mainThread = Thread.currentThread();
Thread joinThread = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
try {
if ( i % 2 == 0) {
Thread.yield();
System.out.println("应该是礼让线程执行");
}
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "子线程");
} catch (Exception e) {
}
}
},"线程A");
joinThread.start();
for (int i = 0; i < 1000; i++) {
Thread.sleep(1000);
System.out.println("当前主线程" + mainThread);
}
}
}
多线程的引入是在为了能在尽可能的提高效率,但是操作不当是会出现问题的。
class Thread1 implements Runnable {
private Integer ticket = 5;
@Override
public void run() {//线程运行的主方法
synchronized(this) {
while (true) {
if (ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖票" + "当前剩余票数" + (--ticket));
} else {
break;
}
}
}
}
}
public class MyThread {
public static int ticket = 5;
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
for (int i = 0; i < 5; i++) {
new Thread(thread1,"售票机" + i).start();
}
}
}
public class MyThread {
public static int ticket = 5;
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
for (int i = 0; i < 5; i++) {
new Thread(() -> {
hello();
},"售票机" + i).start();
}
}
public static synchronized boolean hello() {
while (true) {
if (ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖票" + "当前剩余票数" + (--ticket));
return true;
} else {
return false;
}
}
}
}
class Book {//描述的书资源
}
class Paint {//描述回话资源
}
public class LockTest {
public static void main(String[] args) {
Book book = new Book();
Paint paint = new Paint();
Thread threadA = new Thread(() -> {
synchronized(book) {
System.out.println("A对B说,你借给我回话资源,我再给你书资源");
try {
Thread.sleep(10000);
//现在A要锁paint资源
synchronized(paint) {
System.out.println("A得到了回话资源");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"线程A");
Thread threadB = new Thread(() -> {
synchronized(paint) {
System.out.println("B对A说,你借给我书资源,我再给你回话资源");
try {
Thread.sleep(10000);
//现在A要锁paint资源
synchronized(book) {
System.out.println("B得到了书资源");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"线程B");
threadA.start();
threadB.start();
}
}
class Message {
private String title;
private String content;
public Message(String title,String content) {
this.title = title;
this.content= content;
}
public Message() {
}
public void setContent(String content) {
this.content = content;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public String getTitle() {
return title;
}
}
class Producer implements Runnable {
Message message;
public Producer(Message message) {
this.message = message;
}
@Override
public void run() {
try {
for (int i = 0; i < 50; i++) {//生成50个产品
if (i % 2 == 0) {
message.setTitle("你");
Thread.sleep(1000);
message.setContent("好");
} else {
message.setTitle("不");
Thread.sleep(1000);
message.setContent("hao");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
Message message;
public Consumer(Message message) {
this.message = message;
}
@Override
public void run() {
try {
for (int i = 0; i < 50; i++) {
System.out.println("消费者 title" + this.message.getTitle() + "content = " + this.message.getContent());
Thread.sleep(1000);
}
} catch (Exception e) {
}
}
}
public class mainClass {
public static void main(String[] args) {
Message message = new Message();
new Thread(new Producer(message)).start();
new Thread(new Consumer(message)).start();
}
}
package cn.mldn.Juc.producerAndcustomer;
class Message {
private String title;
private String content;
public Message(String title,String content) {
this.title = title;
this.content= content;
}
public Message() {
}
public synchronized void setContentAndsetTitle(String content,String title) {
this.content = content;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.title = title;
}
public synchronized String GetString() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Message{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
class Producer implements Runnable {
Message message;
public Producer(Message message) {
this.message = message;
}
@Override
public void run() {
try {
for (int i = 0; i < 50; i++) {//生成50个产品
if (i % 2 == 0) {
message.setContentAndsetTitle("绝地","求生");
Thread.sleep(10000);
} else {
message.setContentAndsetTitle("王者","荣耀");
Thread.sleep(1000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
Message message;
public Consumer(Message message) {
this.message = message;
}
@Override
public void run() {
try {
for (int i = 0; i < 50; i++) {
System.out.println(this.message.GetString());
Thread.sleep(1000);
}
} catch (Exception e) {
}
}
}
public class mainClass {
public static void main(String[] args) {
Message message = new Message();
new Thread(new Producer(message)).start();
new Thread(new Consumer(message)).start();
}
}
class Message {
private String title;
private String content;
boolean flag = true;//等于true为可以生产,不可以消费。为false,可以消费,不可以生产
public Message(String title,String content) {
this.title = title;
this.content= content;
}
public Message() {
}
public synchronized void setContentAndsetTitle(String content,String title) {
if (this.flag == false) {
try {
//说明有消费者线程在执行,等消费者线程执行完毕后唤醒
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.content = content;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.title = title;
//生产完成后,把消费者线程唤醒
this.flag = false;
super.notify();//唤醒其他线程
}
public synchronized String GetString() {
if (flag == true) {
try {
//说明生产者线程在执行,等待生成完成后被唤醒
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//消费完成后,把生产者线程唤醒
this.flag = true;
super.notify();
return "Message{" +
"title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
class Producer implements Runnable {
Message message;
public Producer(Message message) {
this.message = message;
}
@Override
public void run() {
try {
for (int i = 0; i < 50; i++) {//生成50个产品
if (i % 2 == 0) {
message.setContentAndsetTitle("绝地","求生");
Thread.sleep(1000);
} else {
message.setContentAndsetTitle("王者","荣耀");
Thread.sleep(1000);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
Message message;
public Consumer(Message message) {
this.message = message;
}
@Override
public void run() {
try {
for (int i = 0; i < 50; i++) {
System.out.println(this.message.GetString());
Thread.sleep(1000);
}
} catch (Exception e) {
}
}
}
public class mainClass {
public static void main(String[] args) {
Message message = new Message();
new Thread(new Producer(message)).start();
new Thread(new Consumer(message)).start();
}
}
package cn.mldn.Juc.class1;
class Message implements Runnable {
public Message() {
Thread thread = new Thread(() -> {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("守护线程执行");
}
});
thread.setDaemon(true);//设置Thread线程为守护线程
thread.start();
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程执行" + Thread.currentThread().getName() + "执行");
}
}
}
public class WatchThread {
public static void main(String[] args) {
new Thread(new Message()).start();
}
}
package cn.mldn.Juc.class1;
class Message implements Runnable {
private volatile int ticket = 3;
@Override
public void run() {
while (true) {
if (ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("剩余票数位" + (--this.ticket));
} else {
break;
}
}
}
}
public class WatchThread {
public static void main(String[] args) {
Message message = new Message();
new Thread(message,"机器A").start();
new Thread(message,"机器B").start();
}
}
package cn.mldn.Juc.class1;
class Message implements Runnable {
private volatile int ticket = 3;
@Override
public void run() {
while (sale()) {
}
}
public synchronized boolean sale() {
if (ticket > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("剩余票数位" + (--this.ticket));
return true;
} else {
return false;
}
}
}
public class WatchThread {
public static void main(String[] args) {
Message message = new Message();
new Thread(message,"机器A").start();
new Thread(message,"机器B").start();
}
}
package cn.mldn.Juc.class1;
class Message1 {
private int number = 0;
public synchronized void add() {
//1判断
while (number == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2干活
number++;
System.out.println(Thread.currentThread().getName() + "完成工作" + number);
//3通知
this.notifyAll();
}
public synchronized void sub() {
//1判断
while (number != 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2干活
number--;
System.out.println(Thread.currentThread().getName() + "完成工作" + number);
//3通知
this.notifyAll();
}
}
public class InterviewTest {
public static void main(String[] args) {
Message1 message = new Message1();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
message.add();
}
},"一号加法线程").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
message.add();
}
},"二号加法线程").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
message.sub();
}
},"三号减法线程").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
message.sub();
}
},"四号减法线程").start();
}
}
package cn.mldn.Juc.class1;
class Computer {
private String brand;//电脑品牌
private double price;//电脑价格
public Computer(String brand,double price) {
this.brand = brand;
this.price = price;
}
@Override
public String toString() {
return "Computer{" +
":品牌=" + brand + '\'' +
":价格=" + price +
'}';
}
}
class Resource {
private int number = 0;//公共资源电脑数量
private Computer computer = null;//当前电脑
public Resource() {
Thread numberDaemonThread = new Thread(() ->{
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("后台统计线程在统计电脑,当前生产电脑数量为= " + this.number);
}
});
numberDaemonThread.setDaemon(true);
numberDaemonThread.start();
}
public synchronized void create(String brand,double price) {
//首先判断(如果为空,等待消费
while (this.computer != null) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//干活
this.computer = new Computer(brand,price);
this.number ++;
System.out.println("" + Thread.currentThread().getName() + "完成电脑生产完成");
//通知我生产好啦
this.notifyAll();
}
public synchronized void decreate() {
//首先判断(如果为空,等待生产
while (this.computer == null) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//干活
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("" + Thread.currentThread().getName() + "完成搬运");
this.computer = null;
//通知我生产好啦
this.notifyAll();
}
}
public class ComputerTest {
public static void main(String[] args) {
Resource resource = new Resource();
new Thread(() -> {
for (int i = 0; i < 50; i++) {
if (i % 2 == 0) {
resource.create("惠普",6000.00);
} else {
}
}
},"生产线程").start();
new Thread(() -> {
for (int i = 0; i < 50; i++) {
if (i % 2 == 0) {
resource.decreate();
} else {
}
}
},"搬运线程").start();
}
}
package cn.mldn.Juc.class1;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
class Resource1 implements Callable {
private boolean flag;//抢答结果状态
@Override
public String call() throws Exception {
Thread.sleep(1000);
//由于我们要每个线程进行先后执行
synchronized(this) {
if (this.flag == false) {
this.flag = true;
return Thread.currentThread().getName() + "抢答成功";
} else {
return Thread.currentThread().getName() + "抢答失败";
}
}
}
}
public class CallableInterview {
public static void main(String[] args) {
Resource1 resource = new Resource1();
FutureTask futureTask = new FutureTask<>(resource);
FutureTask futureTask1 = new FutureTask<>(resource);
FutureTask futureTask2 = new FutureTask<>(resource);
new Thread(futureTask,"抢答人A").start();
new Thread(futureTask1,"抢答人B").start();
new Thread(futureTask2,"抢答人C").start();
}
}
并发:多个线程去抢占同一个资源
并行:两件事情同时进行【你在看视频和做笔记】
java.util.concurrent
java.util.concurrent.atomic
java.util.concurrent.locks
在高内聚低耦合的前提下,线程,操作,资源类
package cn.mldn.Juc.class2;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
public class SaleTicket {
public static void main(String[] args) {
//在高内聚低耦合的前提下(其实就是一个类,如果想去操作,必须去通过方法去调用)
//1、先创建资源类(在高内聚低耦合的前提下)
Ticket ticket = new Ticket();
//2、创建线程 3、操作
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}
},"线程1").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}
},"线程2").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
}
},"线程3").start();
}
}
class Ticket {//资源类就是一个类[内聚就是要聚变量]
private int number = 30;
Lock lock = new ReentrantLock();
public void sale() {
lock.lock();
try {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出" + (number --) + "还剩下:" + number);
}
} catch (Exception e) {
} finally {
lock.unlock();
}
}
}
public class SaleTicket {
public static void main(String[] args) {
//在高内聚低耦合的前提下(其实就是一个类,如果想去操作,必须去通过方法去调用)
//1、先创建资源类(在高内聚低耦合的前提下)
Ticket ticket = new Ticket();
//2、创建线程 3、操作
new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
},"线程3").start();
new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
},"线程2").start();
new Thread(() -> {
for (int i = 0; i < 40; i++) {
ticket.sale();
}
},"线程1").start();
}
}
class Ticket {//资源类就是一个类[内聚就是要聚变量]
private int number = 30;
Lock lock = new ReentrantLock();
public void sale() {
lock.lock();
try {
if (number > 0) {
System.out.println(Thread.currentThread().getName() + "卖出" + (number --) + "还剩下:" + number);
}
} catch (Exception e) {
} finally {
lock.unlock();
}
}
}