Java.Thread 多线程
继承Thread类 重写run方法
public class TestThreadClass extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
实现Runnable 接口 重写run方法
public class TestThread implements Runnable {
private int ticketNums = 10; //模拟票数
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) {
TestThread testThread = new TestThread();
new Thread(testThread,"User1").start();
new Thread(testThread,"User2").start();
new Thread(testThread,"User3").start();
}
}
Callable 接口 重写call方法
public class TestCallable implements Callable {
public Object call() throws Exception {
return "测试callable";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable testCallable = new TestCallable();
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<?> result = executorService.submit(testCallable);
Object o = result.get();
executorService.shutdownNow();
System.out.println(o);
}
}
龟兔赛跑
public class Race implements Runnable {
//定义胜利者 默认是null
private static String winner;
public void run() {
for (int i = 1; i <= 100 ; i++) {
if (Thread.currentThread().getName().equals("rabbit")){
//让兔子睡觉
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameOver(i);
//true gameOver;
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"->> run "+i+" step");
}
}
//判断游戏是否结束
public boolean gameOver(int steps){
if (winner != null){
return true;
}{
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,"tortoise").start();
new Thread(race,"rabbit").start();
}
}
线程的五种状态
new Thread 新生状态
.start方法 就绪状态
cpu运行代码 运行状态
.sleep wait方法 阻塞状态
自然结束,外部干涉 死亡状态
sleep方法 打印当前系统时间
public class TestSleep {
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 (InterruptedException e) {
e.printStackTrace();
}
}
}
}
守护线程 deamon
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕
如:后台的操作日志,垃圾回收GC
public class Testdaemon {
public static void main(String[] args) {
You you = new You();
God god = new God();
Thread thread = new Thread(god);
thread.setDaemon(true);
thread.start();
new Thread(you).start();
}
}
class God implements Runnable {
public void run() {
while (true) {
System.out.println("上帝保佑着你");
}
}
}
class You implements Runnable {
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你活着");
}
System.out.println("-->>goodbye world");
}
}
并发问题 多个线程操作同一个资源的时候 synchronized
public class TestList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
CopyOnWriteArrayList 线程安全的
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
死锁
//死锁
public class DeadLock {
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 name;
Makeup(int choice,String name){
this.choice = choice;
this.name = name;
}
@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.name+"获得口红的锁");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(this.name+"获得镜子的锁");
}
}
}else {
synchronized (mirror){
System.out.println(this.name+"获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick){
System.out.println(this.name+"获得口红的锁");
}
}
}
}
}
ReentrantLock 显示锁
public class TestLock {
public static void main(String[] args) {
TestReentrantLock lock = new TestReentrantLock();
new Thread(lock).start();
new Thread(lock).start();
new Thread(lock).start();
}
}
class TestReentrantLock implements Runnable{
int ticketNums = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ticketNums>0){
System.out.println(ticketNums--);
}else {
break;
}
}finally {
lock.unlock();
}
}
}
}
生产者消费者模型–>利用缓冲区解决:管程法
//生产者 消费者 产品 缓冲区
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 = 1 ; 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 = 1; 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(count == chickens.length){
//通知消费,等待生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//没有满,生产产品放入产品
chickens[count] = chicken;
count++;
//通知消费
this.notifyAll();
}
//消费产品
public synchronized Chicken pop(){
//判断能否消费
if(count == 0){
//生产者生产 消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费者拿走产品
count--;
Chicken chicken = chickens[count];
//通知生产
this.notifyAll();
return chicken;
}
}
信号灯法 通过标志位解决
//信号灯法 通过标志位解决
public class TestSignal {
public static void main(String[] args) {
Tv tv = new Tv();
new Player(tv).start();
new Wather(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++) {
this.tv.play("<快乐大本营>");
}
}
}
//观众
class Wather extends Thread{
Tv tv;
public Wather(Tv tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
this.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 = !flag;
}
//观看
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
this.notify();
this.flag = !flag;
}
}
线程池 Executors工具类 工厂类 创建线程
public class TestPool {
public static void main(String[] args) {
MyThread myThread = new MyThread();
//创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
//执行
executorService.execute(myThread);
executorService.execute(myThread);
executorService.execute(myThread);
executorService.execute(myThread);
//关闭
executorService.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}