线程的状态
lambda
public class TestLambda1 {
//3.静态类
static class Lake2 implements Ilake{
@Override
public void lambda() {
System.out.println("I Lake lambda2");
}
}
public static void main(String[] args) {
Ilake like = new Lake();
like.lambda();
like = new Lake2();
like.lambda();
class Lake3 implements Ilake{
@Override
public void lambda() {
System.out.println("I Lake lambda3");
}
}
like = new Lake3();
like.lambda();
//5.匿名内部类,没有类的名称,必须借助接口或者父类
like = new Ilake() {
@Override
public void lambda() {
System.out.println("I Lake lambda4");
}
};
like.lambda();
//6.用lambda简化
like = ()-> {
System.out.println("I Lake lambda5");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface Ilake{
void lambda();
}
//2.实现类
class Lake implements Ilake{
@Override
public void lambda() {
System.out.println("I Lake lambda");
}
}
join
//测试join方法//想象插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("线程vip来了"+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 < 1000; i++) {
if (i==200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
插队
yield
public class TestYield {
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()+"线程停止执行");
}
}
priority
//测试线程优先级
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5 = new Thread(myPriority);
Thread t6 = new Thread(myPriority);
t1.start();
t2.setPriority(10);
t2.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
Daemon
//守护线程
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true);
thread.start();
new Thread(you).start();
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("上帝保佑你!");
}
}
}
//me
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一生都开心活着");
}
System.out.println("=========goodbye!World!========");
}
}
state
//观察测试线程的状态
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) {
throw new RuntimeException(e);
}
}
System.out.println("///////");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//new
//观察启动后
thread.start();
state = thread.getState();
System.out.println(state);//run
while (state != Thread.State.TERMINATED){
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
}
}
线程同步以及不安全的解决
synchronized ()锁的对象一定是变化的量,需要增删改查的量
synchronized块解决不安全
package com.zzl.Demo1;
//不安全的取钱
//两个人去取钱
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100,"结婚基金");
Drawing you = new Drawing(account,50,"你");
Drawing girlFriend = new Drawing(account,100,"girlFriend");
you.start();
girlFriend.start();
}
}
//账户
class Account{
int money;
String name;
public Account(int money,String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account, int drawingMoney, String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
this.nowMoney = nowMoney;
}
@Override
public void run() {
// synchronized块解决不安全
//锁的对象一定是变化的量,需要增删改查的量
synchronized (account){
//判断没有钱
if (account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money = account.money-drawingMoney;
//你手里的前
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+ "余额为" +account.money);
//Thread.currentThread().getName()= this.getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
}
package com.zzl.Demo1;
import java.util.ArrayList;
import java.util.List;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(1_000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
synchronized解决不安全
package com.zzl.Demo1;
//线程不安全
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"苦逼的我").start();
new Thread(station,"牛逼的你们").start();
new Thread(station,"可恶的黄牛党").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止
@Override
public void run() {
//买票
while (flag){
buy();
}
}
//synchronized解决不安全
private synchronized void buy(){
// 判断是否邮票
if (ticketNums<=0){
flag = false;
return;
}{
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
}
锁
死锁
package com.zzl.Demo1;
public class DeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0,"灰姑凉");
Makeup makeup2 = new Makeup(1,"白雪公主");
makeup2.start();
makeup.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(1000);
}
synchronized (lipstick) {
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
锁
package com.zzl.Demo1;
import java.util.concurrent.locks.ReentrantLock;
//ReentrantLock可重复锁
//测试Lock锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if (ticketNums>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
} finally {
lock.unlock();//解锁
}
}
}
}
消费者和生产者问题
package com.zzl.Demo1;
//测试:生产者消费者模拟--》利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
class Productor extends Thread{
SynContainer container;
public Productor(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+"kun");
}
}
}
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+"kun");
}
}
}
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 (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--;
Chicken chicken = chickens[count];
this.notify();
//吃完了,通知消费者生产
return chicken;
}
}
package com.zzl.Demo1;
//测试生产者消费者问题2:信号灯法
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++) {
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.notify();//通知唤醒
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.notify();
this.flag = !this.flag;
}}
总结
package com.zzl.Demo1;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//1,回顾总结线程的创建
public class ThreadNew {
public static void main(String[] args) {
//1.继承Thread类
new MyThread1().start();
//2.实现Runable接口
new Thread(new MyThread2()).start();
//3.实现Callable接口
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();//两种方法
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();;
}
}
}
//1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1");
}
}
//2.实现Runable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
//3.实现Callable接口
class MyThread3 implements Callable{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}
标签:Thread,void,class,线程,完结,println,new,public
From: https://www.cnblogs.com/zzl990110/p/18003762