//创建线程方式以:继承Thread类,重写run()方法,调用start开启线程
//线程开启后不一定立即执行,由cpu调度来执行
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i <20; i++) {
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args) {
//main线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 200; i++) {
System.out.println("我在学习多线程"+i);
}
}
}
package com.ran.threads;
//多个线程同时操作一个对象
//买火车票的例子
public class TestThread4 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) {
TestThread4 ticket = new TestThread4();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛党").start();
}
}
在这段代码的执行中会出现两个人同时拿到一张票的情况,这种情况就是并发问题。
package com.ran.threads;
//静态代理模式
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//优点:
//代理对象可以做很多真实对象做不了的事情
//真实对象专注做自己的事情
public class StaticProxy {
public static void main(String[] args) {
You you = new You();
WeddingCompany weddingCompany = new WeddingCompany(you);
weddingCompany.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实角色
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("结婚了");
}
}
//代理角色
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
其实质输入函数式编程的概念
(params)->expression[表达式]
(parans)->statement[语句]
(params)->{statements}
为什么要使用lambda表达式
理解Functional Interface(函数式接口)是学习Java8 lambda表达式的关键所在。
函数式接口的定义:
` 简化过程:函数式接口-->实现类-->静态内部类-->局部内部类-->匿名内部类-->lambda表达式
public class TestLambda1 {
//静态内部类
static class Like2 implements ILike{
@Override
public void like() {
System.out.println("like2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.like();
like = new Like2();
like.like();
//局部内部类
class Like3 implements ILike{
@Override
public void like() {
System.out.println("like3");
}
}
like = new Like3();
like.like();
//匿名内部类
like= new Like() {
@Override
public void like() {
System.out.println("like4");
}
};
like.like();
//用lambda简化
like = ()->{
System.out.println("like5");
};
like.like();
}
}
//1.定义一个函数式接口
interface ILike{
void like();
}
//2.实现类
class Like implements ILike{
@Override
public void like() {
System.out.println("like1");
}
}
public class TestLambda2{
public static void main(String[] args) {
ILove love;
love = (a,b)->{
System.out.println("love"+a);
};
//总结:
//lambda表达式只能有一行代码的情况下才能简化成一行,如果有多行,就用代码块包裹
//前提是接口为函数式接口
//多个参数也可以去掉参数类型,要去掉就都去掉,多个参数的情况下必须加上括号
love.Love(200,300);
}
}
interface ILove{
void Love(int a,int b);
}
setPriority(int newPriority) | 更改现成的优先级 |
static void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程,别用这个方式 |
boolean isAlive() | 测试线程是否处于活动状态 |
不推荐使用JDK提供的stop()、destroy()方法。这两个方法已经废弃。
推荐让线程自己停止下来
建议使用一个标识位进行终止变量,当flag=false,则终止线程运行。
public class TestStop implements Runnable{
//1.设置一个标识位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run...thread"+i++);
}
}
//2.设置一个公开的方法停止进程,转换标识位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
testStop.stop();//3.运行停止进程的方法
System.out.println("线程停止");
}
}
}
}
sleep指定当前线程阻塞的毫秒数;
sleep存在一场InterruptedException;
sleep时间达到后线程进入就绪状态;
sleep可以模拟网络延时,倒计时等;
每个对象都有一个锁,sleep不会释放锁;
//用sleep模拟10s倒计时
public class TestSleepDemo01{
public void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if(num<0){
break;
}
}
}
public static void main(String[] args) throws InterruptedException {
TestSleepDemo01 testSleepDemo01 = new TestSleepDemo01();
testSleepDemo01.tenDown();
}
}
//用sleep输出每秒的当前时间输出
public static void main(String[] args) {
//打印当前系统时间
Date startTime = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
礼让线程,让当前正在执行的线程暂停,但不阻塞。
将线程从运行状态转为就绪状态。
让cpu重新调度,礼让不一定成功。
public class TestYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"进程开始");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"进程结束");
}
public static void main(String[] args) {
TestYield testYield = new TestYield();
new Thread(testYield,"a").start();
new Thread(testYield,"b").start();
}
}
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
可以想象成插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 1; i < 100; i++) {
System.out.println("插队人员..."+i);
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 100; i++) {
if (i==50){
thread.join();//插队,从此开始只运行插队的这一个线程,其他线程阻塞
}
System.out.println("正常排队人员..."+i);
}
}
}
public class TestState{
public static void main(String[] args) throws InterruptedException {
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);//NEW
//启动后
thread.start();
state=thread.getState();
System.out.println(state);//RUNNABLE
while (state!=Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState();
System.out.println(state);
}
}
}
线程分为用户线程和守护线程
虚拟机必须雀报用户线程执行完毕
虚拟机不用等待守护线程执行完毕
如:后台记录操作日志,监控内存,垃圾回收等待等
setDaemon(boolean)
来设置一个线程是否为守护线程,默认值是false代表这个线程是一个用户线程
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块。
同步方法:public synchronized void method(int args){}
synchronized 方法控制“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法申明为synchronized将会影响效率。
class A{
private final ReentrantLock lock = new ReentrantLock();
public void m(){
lock.lock();//加锁
try{
//保证线程安全的代码
}finally{//不管有没有异常被抛出、捕获,finally块都会被执行
lock.unlock();//解锁
//如果同步代码有一场,要将unlock()写入finally语句块
}
}
}
//生产者消费者问题:管程法
public class TestPC {
public static void main(String[] args) {
SynContainer container=new SynContainer();
new Producter(container).start();
new Consumer(container).start();
}
}
//产品
class Chicken{
int id;
public Chicken(int id){
this.id=id;
}
}
//生产者
class Producter extends Thread{
SynContainer container;
public Producter(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 SynContainer{
//设定容器大小
Chicken[] chickens=new Chicken[100];
//容器计数器
int count=0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费
if(count==chickens.length){
//通知消费者消费,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,就需要丢入产品
chickens[count]=chicken;
count++;
//通知消费者消费
this.notify();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断能否消费
if(count==0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
count--;
//唤醒生产者生产
this.notify();
//吃完了,等待生产者生产
return chickens[count];
}
}
//生产者消费者问题:信号灯法,标志位解决
public class TestPC2 {
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++) {
if (i%2==0){
this.tv.watch("快乐大本营");
}else {
this.tv.watch("天天向上");
}
}
}
}
//产品——》节目
class TV{
//演员表演,观众等待 T
//观众观看,演员等待 F
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.notify();//唤醒观众
this.voice=voice;
this.flag=!this.flag;
}
//观看
public synchronized void watch(String voice){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
//通知演员表演
this.notify();//唤醒演员
this.flag=!this.flag;
}
}
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁常见销毁、实现重复利用。类似生活中的公共交通工具。
好处:
JDK 5.0起提供了线程池相关API:ExecutorService 和Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//1,创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
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());
}
}
原文:https://www.cnblogs.com/RanStudy/p/14618735.html