// 1. 继承Thead类
public class TestThead extends Thread{
// 2. 重写run方法
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("多线程执行-----" + i);
}
}
public static void main(String[] args) {
// 3. 创建实例并执行start()方法
TestThead testThead = new TestThead();
testThead.start();
for (int i = 0; i < 500; i++) {
System.out.println("主线执行-----" + i);
}
}
}
// 1,实现Runable接口
public class TestTherd implements Runnable{
// 2,重写run方法
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("多线程执行 --- " + i);
}
}
public static void main(String[] args) {
// 3,创建对象实例并使用静态代理执行start方法
new Thread(new TestTherd()).start();
for (int i = 0; i < 200; i++) {
System.out.println("主线程执行 -- " + i);
}
}
}
/**
* @author: mingan.xie
* @since: 2020/6/23 20:12
* @email:
*/
// Callable实现多线程
// 1,实现Callable接口,泛型类型与call方法的返回值类型一致
public class TestCallable implements Callable<Boolean> {
// 2,重写call方法
@Override
public Boolean call() throws Exception {
System.out.println("线程执行了");
}
public static void main(String[] args) {
// 3,创建实例
TestCallable testCallable1 = new TestCallable();
TestCallable testCallable2 = new TestCallable();
TestCallable testCallable3 = new TestCallable();
// 4,创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 5,提交执行
Future<Boolean> future1 = executorService.submit(testCallable1);
Future<Boolean> future2 = executorService.submit(testCallable2);
Future<Boolean> future3 = executorService.submit(testCallable3);
// 6,关闭服务
executorService.shutdownNow();
}
}
必须是函数式接口,即只有一个方法的接口
/**
* @author: mingan.xie
* @since: 2020/6/23 21:01
* @email:
*/
public class TestLamda {
public static void main(String[] args) {
EatRice eatRice = new EatRice() {
@Override
public void rice() {
System.out.println("匿名内部类吃饭了");
}
};
eatRice.rice();
eatRice = () -> {
System.out.println("lamda表达式吃饭了");
};
eatRice = () -> System.out.println("lamda表达式吃饭了");
eatRice.rice();
}
}
interface EatRice{
void rice();
}
class Me implements EatRice{
@Override
public void rice() {
System.out.println("吃饭了");
}
}
建议使用一个标志位来停止线程
/**
* @author: mingan.xie
* @since: 2020/6/25 8:24
* @email:
*/
// 停止线程:
// 不建议手动停止线程,建议使用一个标志位来停止线程
public class TestStop implements Runnable{
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("Thrad ---> " + i++);
}
}
public void stop(){
flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
if (i == 800){
testStop.flag = false;
}
System.out.println("main ---> " + i);
}
}
}
/**
* @author: mingan.xie
* @since: 2020/6/25 8:52
* @email:
*/
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(new TestYield(),"a").start();
new Thread(new TestYield(),"b").start();
}
}
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度按照优先级决定应该调度那个线程执行
在调用star方法执行前设置优先级
/**
* @author: mingan.xie
* @since: 2020/6/25 9:20
* @email:
*/
public class TestPriority {
public static void main(String[] args) {
// 主线程优先级默认为5
System.out.println(Thread.currentThread().getName() + "main线程执行 ---》" + Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread threada = new Thread(myPriority, "a");
threada.setPriority(1);
threada.start();
Thread threadb = new Thread(myPriority, "b");
threadb.setPriority(Thread.NORM_PRIORITY);
threadb.start();
Thread threadc = new Thread(myPriority, "c");
threada.setPriority(8);
threadc.start();
Thread threadd = new Thread(myPriority, "d");
threadd.setPriority(Thread.MAX_PRIORITY);
threadd.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程执行 ---》" + Thread.currentThread().getPriority());
}
}
线程分为用户线程和守护线程
虚拟机必须再确认用户线程执行完毕后才能关闭,不用等待守护线程执行完毕
常见实例:日志操作,立即回收,内存监控
/**
* @author: mingan.xie
* @since: 2020/6/25 9:36
* @email:
*/
public class TestDaemon {
public static void main(String[] args) {
Thread thread = new Thread(new Word());
// 设置线程为守护线程,默认为false(用户线程)
thread.setDaemon(true);
thread.start();
// 主线程
new Thread(new You()).start();
}
}
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("你开心的活着 ---> " + i + " 天");
}
System.out.println("=============== good byd==============");
}
}
class Word implements Runnable{
@Override
public void run() {
while (true){
System.out.println("地球养育着你");
}
}
}
/**
* @author: mingan.xie
* @since: 2020/6/27 10:28
* @email:
*/
public class ReenTantLock {
public static void main(String[] args) {
Tickets tickets = new Tickets();
new Thread(tickets,"A").start();
new Thread(tickets,"B").start();
new Thread(tickets,"C").start();
}
}
class Tickets implements Runnable{
private int num = 10;
private ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();
Thread.sleep(200);
if (num > 0){
System.out.println(num--);
}else{
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
package com.demo06;
/**
* @author: mingan.xie
* @since: 2020/6/27 10:56
* @email:
*/
public class TestPC {
public static void main(String[] args) {
Buffer buffer = new Buffer();
new Thread(new Producer(buffer)).start();
new Thread(new Consumer(buffer)).start();
}
}
// 生产者
class Producer implements Runnable{
Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
buffer.push(new Chicken(i));
System.out.println("生产了第:" + i+"只");
}
}
}
// 消费者
class Consumer implements Runnable{
Buffer buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Chicken pop = buffer.pop();
System.out.println("消费了第 ===》 "+pop.id+"值");
}
}
}
// 产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
// 缓冲区
class Buffer implements Runnable{
Chicken[] buffers = new Chicken[10];
int num = 0;
synchronized void push(Chicken chicken){
// 如果容器满了,就进入等待状态
if (num == buffers.length){
try {
this.wait();
return;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 如果没有满,就添加
buffers[num] = chicken;
num++;
// 通知消费者消费
this.notifyAll();
}
synchronized Chicken pop(){
// 判断是否容器是否空了,就进入等待状态,等生产者生产
if (num == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 消费
num--;
Chicken buffer = buffers[num];
// 唤起生产者生产产品
this.notifyAll();
return buffer;
}
@Override
public void run() {
}
}
package com.demo06;
/**
* @author: mingan.xie
* @since: 2020/6/27 11:32
* @email:
*/
// 线程通信方法:信号灯法
public class TestPC2 {
public static void main(String[] args) {
Program program = new Program();
new Thread(new Perform(program)).start();
new Thread(new Audience(program)).start();
}
}
// 生产者
class Perform implements Runnable {
Program program;
public Perform(Program program) {
this.program = program;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i % 2 == 0) {
program.play("新闻联播");
} else {
program.play("花样广告");
}
}
}
}
// 消费者
class Audience implements Runnable {
Program program;
public Audience(Program program) {
this.program = program;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
program.wacth();
}
}
}
class Program implements Runnable {
// 控制状态的切换
boolean flag = true;
String view;
synchronized void play(String view) {
// flag: t -> 生产 、 f -> 消费
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 生产者生产
System.out.println("演员生产了" + view);
this.view = view;
this.flag = !this.flag;
// 唤醒消费者消费
this.notifyAll();
}
synchronized void wacth() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 消费者消费
System.out.println("消费者观看了:" + view);
this.flag = !this.flag;
// 唤醒生产者生产
this.notifyAll();
}
@Override
public void run() {
}
}
package com.demo06;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author: mingan.xie
* @since: 2020/6/27 12:14
* @email:
*/
public class TestPool {
public static void main(String[] args) {
MyThread myThread = new MyThread();
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(myThread);
service.execute(myThread);
service.execute(myThread);
service.execute(myThread);
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}