思维导图
线程的创建
package com.lxf.thread;
//创建线程 继承thread类 重写run方法
public class ThreadDemo01 extends Thread {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码"+i);
}
}
public static void main(String[] args) {
ThreadDemo01 threadDemo = new ThreadDemo01();
//线程创建不一定会县执行·
threadDemo.start();
threadDemo.run();
for (int i = 0; i < 1000; i++) {
System.out.println("我在看java"+i);
}
}
}
package com.lxf.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//创建线程 继承thread类 重写run方法
public class ThreadDemo02 extends Thread {
private String url ;
private String name ;
public ThreadDemo02(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downloader(url,name);
System.out.println("文件已经下载"+name);
}
public static void main(String[] args) {
ThreadDemo02 t1 = new ThreadDemo02("https://profile.csdnimg.cn/F/F/3/1_u012391293","1.jpg");
ThreadDemo02 t2 = new ThreadDemo02("https://img-blog.csdnimg.cn/20190927151026427.png?x-oss-process=image/resize,m_fixed,h_64,w_64","2.jpg");
ThreadDemo02 t3 = new ThreadDemo02("https://img-blog.csdnimg.cn/20190918140158853.png?x-oss-process=image/resize,m_fixed,h_64,w_64","3.jpg");
t1.start();
t2.start();
t3.start();
}
class WebDownLoader{
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader出现问题");
}
}
}
}
java.接口
线程创建
package com.lxf.thread;
//创建线程方式2:实现Runnable 接口 重写run方法 执行线程需要丢人runnable 接口实现类 调用start方法
public class ThreadDemo03 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码"+i);
}
}
public static void main(String[] args) {
ThreadDemo03 threadDemo03 = new ThreadDemo03();
Thread thread = new Thread(threadDemo03);
thread.start();
// thread.run();
for (int i = 0; i < 100; i++) {
System.out.println("我在看java"+i);
}
}
}
多线程操作同一对象
package com.lxf.thread;
public class ThreadDemo04 implements Runnable {
//多线程操作同一对象
//多个线程操作同一个对象 会造成线程紊乱数据不安全
private int ticketNums = 10 ;
@Override
public void run() {
while (true){
if (ticketNums <= 0){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"票");
}
}
public static void main(String[] args) {
ThreadDemo04 ticket = new ThreadDemo04();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛").start();
}
}
龟兔赛跑
package com.lxf.thread;
public class Race implements Runnable {
private static String winner ;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子") && i%10 == 0){ //当前线程为兔子且每10步的时候休息一次
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameOver(i); //判断游戏结束
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"-->跑了"+i+"步");
}
}
private boolean gameOver(int steps) {
if (winner != null) {
return true;
}else {
if (steps >= 100){
winner = Thread.currentThread().getName();
System.out.println(winner+" is winner");
return true ;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
Java.Callable
call方法
- 可以定义返回值
- 可以抛出异常
package com.lxf.thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//创建线程方式3 实现callable接口
public class ThreadDemo05 implements Callable<Boolean> {
private String url ;
private String name ;
public ThreadDemo05(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public Boolean call () {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downloader(url,name);
System.out.println("文件已经下载"+name);
return true ;
}
public static void main(String[] args) throws ExecutionException,InterruptedException {
ThreadDemo05 t1 = new ThreadDemo05("https://profile.csdnimg.cn/F/F/3/1_u012391293","1.jpg");
ThreadDemo05 t2 = new ThreadDemo05("https://img-blog.csdnimg.cn/20190927151026427.png?x-oss-process=image/resize,m_fixed,h_64,w_64","2.jpg");
ThreadDemo05 t3 = new ThreadDemo05("https://img-blog.csdnimg.cn/20190918140158853.png?x-oss-process=image/resize,m_fixed,h_64,w_64","3.jpg");
//创建执行服务
ExecutorService service = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = service.submit(t1) ;
Future<Boolean> r2 = service.submit(t2) ;
Future<Boolean> r3 = service.submit(t3) ;
//获取结果
boolean rs1 = r1.get();
boolean rs2 = r2.get();
boolean rs3 = r3.get();
//关闭服务
service.shutdown();
}
//下载方法
class WebDownLoader{
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader出现问题");
}
}
}
}
静态代理
package com.lxf.thread;
public class StaticDemo {
public static void main(String[] args) {
new Thread(() -> System.out.println("woaini")).start();
new WeddingCompany(new You()).HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
class you implements Marry{
@Override
public void HappyMarry() {
System.out.println("Marry++++");
}
}
class WeddingCompany implements Marry{
private Marry target ;
public WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();
after();
}
private void after() {
System.out.println("结婚之后");
}
private void before() {
System.out.println("结婚之前");
}
}
Lambda 表达式
Java 8的一个大亮点是引入Lambda表达式,使用它设计的代码会更加简洁。当开发者在编写Lambda表达式时,也会随之被编译成一个函数式接口(只有一个方法的接口)。
package com.lxf.thread;
public class LambdaDemo {
//静态内部类
static class Like2 implements ILike {
@Override
public void lambda() {
System.out.println("i like lambda2");
}
}
//静态内部类
public static void main(String[] args) {
ILike like = new Like();
like.lambda();
new Like2().lambda();
//局部内部类
class Like3 implements ILike {
@Override
public void lambda() {
System.out.println("i like lambda3");
}
}
new Like3().lambda();
//匿名内部类
like = new ILike () {
@Override
public void lambda() {
System.out.println("i like lambda4");
}
};
like.lambda();
//lambda
like = () ->{
System.out.println("i like lambda5");
};
like.lambda();
//带参数
//lambda
love = (int a) ->{
System.out.println("i like lambda-->" + a);
};
love.love(5);
//代码多行,参数多个
love = (a) ->{
System.out.println("i like lambda-->" + a);
};
love.love(6);
love = a ->{
System.out.println("i like lambda-->" + a);
};
love.love(7);
//代码只有一行,参数只有一个
love = a -> System.out.println("i like lambda-->" + a );
love.love(8);
}
}
interface ILike{
void lambda();
}
interface ILove{
void love(int a);
}
//实现类
class Like implements ILike {
@Override
public void lambda() {
System.out.println("i like lambda1");
}
}
正如你所看到的,使用Lambda表达式不仅让代码变的简单、而且可读、最重要的是代码量也随之减少很多。然而,在某种程度上,这些功能在Scala等这些JVM语言里已经被广泛使用。
并不奇怪,Scala社区是难以置信的,因为许多Java 8里的内容看起来就像是从Scala里搬过来的。在某种程度上,Java 8的语法要比Scala的更详细但不是很清晰,但这并不能说明什么,如果可以,它可能会像Scala那样构建Lambda表达式。
一方面,如果Java继续围绕Lambda来发展和实现Scala都已经实现的功能,那么可能就不需要Scala了。另一方面,如果它只提供一些核心的功能,例如帮助匿名内部类,那么Scala和其他语言将会继续茁壮成长,并且有可能会凌驾于Java之上。其实这才是最好的结果,有竞争才有进步,其它语言继续发展和成长,并且无需担心是否会过时。
线程方法
线程停止
线程休眠
package com.lxf.thread;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeThreadDemo {
public static void main(String[] args) {
Date date = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
线程礼让
package com.lxf.thread;
//不一定成功
public class ThreadYieldDemo {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
//Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
线程强制执行
package com.lxf.thread;
public class ThreadJoinDemo {
public static void main(String[] args) {
MyJoin myJoin = new MyJoin();
Thread thread = new Thread(myJoin);
thread.start();
for (int i = 0; i < 1000; i++) {
if (i == 200 ){
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("main线程"+i);
}
}
}
class MyJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程VIP"+i);
}
}
}
观察线程的状态
new runnable blocked waiting timed_waiting terrminnated
package com.lxf.thread;
//观察测试线程的状体
public class ThreadStateDemo {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(".......");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//观察启动后
thread.start();
state = thread.getState();
System.out.println(state);
while (state != Thread.State.TERMINATED){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = thread.getState();
System.out.println(state);
}
thread.start();//线程死亡后无法启动
}
}
线程优先级
package com.lxf.thread;
public class ThreadPriorityDemo {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority,"1");
Thread t2 = new Thread(myPriority,"2");
Thread t3 = new Thread(myPriority,"3");
Thread t4 = new Thread(myPriority,"4");
// Thread t5 = new Thread(myPriority);
// Thread t6 = new Thread(myPriority);
//现设置优先级
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t1.setPriority(1);
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(1);
t3.start();
// t5.setPriority(-1);
// t5.start();
// t6.setPriority(11);
// t6.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护(daemon)进程
package com.lxf.thread;
public class DaemonDemo {
public static void main(String[] args) {
God god = new God();
User user = new User();
Thread thread = new Thread(god);
thread.setDaemon(true);
thread.start();
Thread thread1 = new Thread(user);
thread1.start();
}
}
class God implements Runnable {
@Override
public void run() {
while (true){
System.out.println("守护进程");
}
}
}
class User implements Runnable {
@Override
public void run() {
for (int i = 0; i < 30; i++) {
System.out.println("用户进程");
}
System.out.println("用户进程结束=================");
}
}
线程同步
排队、锁 synchronized
// synchronized
private synchronized void Buy() throws InterruptedException{
//判断是否有票
if (ticketNums <= 0 ){
flag =false ;
return;
}
Thread.sleep(200);
System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--);
}
//CopyOnWriteArrayList
public class JUCDemo {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
package com.lxf.syn;
public class LockDemo {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"人1");
Makeup g2 = new Makeup(1,"人2");
g1.start();
g2.start();
}
}
class Lipstick{
}
class Mirror{
}
class Makeup extends Thread {
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice ;
String girlName;
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException{
if (choice == 0){
synchronized (lipstick) {
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
}
}else {
synchronized (mirror) {
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
显示定义同步锁Lock
ReentrantLock
package com.lxf.syn;
import java.util.concurrent.locks.ReentrantLock;
public class LockDemo1 {
public static void main(String[] args) {
Lock1 lock1 = new Lock1();
new Thread(lock1,"a").start();
new Thread(lock1,"b").start();
new Thread(lock1,"c").start();
}
}
class Lock1 implements Runnable {
int tickerNums = 10 ;
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
if (tickerNums > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->"+tickerNums--);
}else {
break;
}
}finally {
lock.unlock();
}
}
}
}
生产、消费模式,定义缓冲区
package com.lxf.syn;
public class PCDemo {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Product(synContainer).start();
new Consumer(synContainer).start();
}
}
class Product extends Thread {
SynContainer container;
public Product(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
}
}
}
class Consumer extends Thread {
SynContainer container;
public Consumer(SynContainer container) {
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了"+container.pop().id+"只鸡");
}
}
}
class Chicken{
int id ;
public Chicken(int id) {
this.id = id;
}
}
class SynContainer{
Chicken[] chickens = new Chicken[10];
int count = 0 ;
public synchronized void push (Chicken chicken){
if (SynContainer.this.count == chickens.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chickens[SynContainer.this.count] = chicken;
SynContainer.this.count++;
this.notifyAll();
}
public synchronized Chicken pop(){
if (SynContainer.this.count == 0 ){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
SynContainer.this.count--;
Chicken chicken = chickens[SynContainer.this.count];
this.notifyAll();
return chicken ;
}
}
信号灯模式 采用标志位控制
package com.lxf.syn;
public class PCDemo2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
class Player extends Thread {
TV tv ;
public Player (TV tv){
this.tv = tv ;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i%2==0){
this.tv.play("快乐大本营");
}else {
this.tv.play("广告");
}
}
}
}
class Watcher extends Thread {
TV tv ;
public Watcher (TV tv){
this.tv = tv ;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
class TV{
String voice ;
boolean flag = true ;
public synchronized void play(String voice){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了:"+voice);
this.notifyAll();
this.voice = voice ;
this.flag = !this.flag;
}
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
this.notifyAll();
this.flag = !this.flag;
}
}
线程池
package com.lxf.syn;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
//创建线程池
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//关闭
service.shutdown();
}
}
class MyThread implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}