/**
* @author xiaomingstu
* @date 2020-06-11 23:35
* 建议线程正常停止---》利用次数,不建议死循环
* 建议使用标识位---》设置一个标识位
* 不要使用stop 或者destroy等过时或者JDK不建议使用的方法
*/
public class ThreadStop implements Runnable {
//设置一个标识位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run......Thread" + i++);
}
}
//设置一个方法停止线程,转换标识位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
ThreadStop threadStop = new ThreadStop();
new Thread(threadStop).start();
for (int i = 0; i < 1000; i++) {
if(i == 900){
threadStop.stop();
System.out.println("—————————线程该停止了!—————————");
}
}
}
}
/**
* @author xiaomingstu
* @date 2020-06-11 23:53
* 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行);
*/
public class ThreadSleep {
/**
* 做一个简易倒计时,10秒钟,控制台每一秒输出一个数字,如10,9,8,7.....0
*/
public static void main(String[] args) throws InterruptedException {
for (int i = 10; i >= 0; i--) {
Thread.sleep(1000);
System.out.println(i);
}
}
}
让当前执行的线程暂停,但不阻塞;
将线程从运行状态转为就绪状态;
让CPU重新调度,礼让不一定成功;
/**
* @author xiaomingstu
* @date 2020-06-16 21:58
*/
public class ThreadYield {
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() + "线程结束执行");
}
}
/**
* @author xiaomingstu
* @date 2020-06-16 22:25
*/
public class ThreadJoin 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{
ThreadJoin join = new ThreadJoin();
Thread thread = new Thread(join);
thread.start();
for (int i = 0; i < 400; i++) {
if(i == 200){
thread.join();
}
System.out.println("main" + i);
}
}
}
public static enum Thread.State
extends Enum<Thread.State>
线程状态。
一个线程可以有以下规定:
NEW
尚未启动的线程处于此状态。
RUNNABLE
在Jave虚拟机中执行的线程处于此状态。
BLOCKED
被阻塞等待监视器锁定的线程处于此状态。
WAITING
正在等待另一个线程执行特定动作的线程处于此状态。
TIMED_WAITING
正在等待另一个线程执行动作达到指定等待时间的线程处于此状态。
TERMINATED
已退出的线程处于此状态。
一个线程可以在给定时间点处于一个状态。这些状态是不反应任何操作系统线程状态的虚拟机状态。
static int ---------MAX_PRIORITY
线程可以拥有的最大优先级。
static int ---------MIN_PRIORITY
线程可以拥有的最小优先级。
static int -------- NORM_PRIORITY
被分配给线程的默认优先级。
void setPriority(int newPriority)
更改此线程的优先级。
int getPriority()
返回此线程的优先级。
/**
* @author xiaomingstu
* @date 2020-06-16 22:55
*/
public class ThreadPriority {
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);
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(3);
t3.start();
t4.setPriority(5);
t4.start();
t5.setPriority(7);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "---------->" + Thread.currentThread().getPriority());
}
}
/**
* @author xiaomingstu
* @date 2020-06-16 23:04
*/
public class ThreadDaemon {
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("上帝保佑着你! ");
}
}
}
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("活着。。。。。。。。。。。");
}
System.out.println("人生不过三万年!");
}
}
同步块: synchronized(obj){}
obj称之为同步监视器
同步监视器的执行过程
同步方法在方法上添加synchronized关键子,锁的是对象本身
从JDK1.5开始,java提供了更为强大的线程同步机制——通过显示定义同步锁对象来实现同步,同步锁使用lock对象来充当
java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中.比较常用的是ReentrantLock,可以显示加锁,释放锁
import org.apache.poi.ss.formula.functions.T;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author xiaomingstu
* @date 2020-06-18 21:32
*/
public class ThreadLock {
public static void main(String[] args) {
LockDemo lockDemo = new LockDemo();
new Thread(lockDemo,"LockA").start();
new Thread(lockDemo,"LockB").start();
new Thread(lockDemo,"LockC").start();
}
}
class LockDemo implements Runnable{
int ticketNums = 10;
//定义Lock锁
private ReentrantLock reentrantLock = new ReentrantLock();
@Override
public void run() {
while (true){
reentrantLock.lock();
try {
if(ticketNums > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "购买了第" + ticketNums-- + "张票");
}else {
break;
}
} finally {
reentrantLock.unlock();
}
}
}
}
生产者和消费者问题
解决方式
并发协作模式"生产者/消费者模式" ===>管程法
/**
* @author xiaomingstu
* @date 2020-06-18 23:00
*/
public class SyncContainer {
//设置容器大小
Product[] products = new Product[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Product product){
//如果容器满了,就通知消费者消费
//通知消费者消费,生产者等待
if(count == products.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
products[count] = product;
count++;
//可以通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronized Product pop() {
//判断容器是否为空
if(count == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//消费
count--;
Product product = products[count];
//通知生产者生产
this.notifyAll();
return product;
}
}
/**
* @author xiaomingstu
* @date 2020-06-18 22:38
*/
public class Product {
private int id;
public Product(int id){
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
/**
* @author xiaomingstu
* @date 2020-06-18 23:24
*/
public class ProviderThread extends Thread {
//创建好的缓冲区
private SyncContainer syncContainer;
public ProviderThread(SyncContainer syncContainer){
this.syncContainer = syncContainer;
}
@Override
public void run(){
for (int i = 0; i < 100; i++) {
System.out.println("生产了" + i +"只鸡!");
syncContainer.push(new Product(i));
}
}
}
/**
* @author xiaomingstu
* @date 2020-06-18 22:50
*/
public class ConsumerThread extends Thread {
private SyncContainer syncContainer;
public ConsumerThread(SyncContainer syncContainer) {
this.syncContainer = syncContainer;
}
@Override
public void run(){
for (int i = 0; i < 100; i++) {
Product pop = syncContainer.pop();
System.out.println("消费了第" + pop.getId() + "号产品!");
}
}
}
/**
* @author xiaomingstu
* @date 2020-06-18 23:28
*/
public class TestMain {
public static void main(String[] args) {
SyncContainer syncContainer = new SyncContainer();
new ProviderThread(syncContainer).start();
new ConsumerThread(syncContainer).start();
}
}
并发协作模式"生产者/消费者模式" ===>信号灯法
//产品-->节目
public 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.voice = voice;
this.notifyAll();
this.flag = !flag;
}
//观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了" + voice);
//通知演员表演
this.notifyAll();
this.flag = !flag;
}
}
public class Player extends Thread {
private TV tv = null;
public Player(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
tv.play("表演了" + i + "号节目");
}
}
}
public class Watcher extends Thread {
private TV tv = null;
public Watcher(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
tv.watch();
}
}
}
//测试生产者消费者问题:信号灯法,标志位解决
public class Main {
public static void main(String[] args) {
TV tv = new TV();
new Watcher(tv).start();
new Player(tv).start();
}
}