1.线程停止
1.建议线程正常停止–》利用次数,不建议死循环
2.建议使用标志位,–》设置一个标志位
3.不要stop,destory等不建议使用的方法
package com.luo.state;
//测试stop
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)
{
//调用stop,切换标志位,让线程停止
testStop.stop();
}
}
}
}
步骤:
1.TestStop类实现接口Runnable,并重写run方法,其中包含线程体,根据标志位flag是否为真,来不断执行线程体
2.设置一个公开的方法停止线程,转换标志位
3.主方法中,创建testStop实例对象,并使用这个对象创建一个新线程,使用start启动该线程。
4.设置主线程体,并当i为900时,使用停止方法,停止线程
2.线程休眠 sleep
步骤:
1.主方法中,获取系统当前时间,创建实例对象startTime,并使用循环,使用线程休眠1秒,再获取系统当前时间,进而实现,再窗口看到时钟。
package com.luo.state;
import java.text.SimpleDateFormat;
import java.util.Date;
//模拟倒计时
public class TestSleep2 {
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();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException{
int num=10;
while (true)
{
Thread.sleep(1000);
System.out.println(num--);
if(num<0)
{
break;
}
}
}
}
3.线程礼让 yield
Thread.yield() 是一个静态的原生方法,用于暂停当前正在执行的线程,使其进入"就绪状态"。在这个状态下,线程并没有被终止,而是被放到等待队列的末尾,等待CPU调度。这是一种让步的行为,可以让其他同优先级或者更高优先级的线程获得执行机会。
具体来说,当一个线程调用了 Thread.yield() 方法后,它就会从"运行状态"变成"就绪状态"。在"就绪状态"下,线程并没有被终止,而是被放到了等待队列的末尾。在下一次CPU调度时,如果有其他的线程需要CPU资源,那么CPU就会选择其他线程进行运行,而不是选择刚刚让步的线程。
然而,需要注意的是,Thread.yield() 的效果并不是百分之百的。因为线程调度器可能会忽略这个提示,仍然让当前线程继续执行。所以,Thread.yield() 并不能保证让当前线程立即停止执行。
package com.luo.state;
//测试礼让
//礼让不一定成功
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()+"线程停止执行");
}
}
4.线程强制执行join
package com.luo.state;
public class TestJoin implements Runnable {
@Override
public void run() {
for(int i=0;i<1000;i++)
{
System.out.println("线程VIP来了!"+i);
try {
Thread.sleep(10); // 添加延时以便观察
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin=new TestJoin();
Thread thread=new Thread(testJoin);
thread.start();
for(int i=0;i<500;i++)
{
if(i==200)
{
thread.join(); // 在这里等待thread线程完成
}
System.out.println("Main"+i);
try {
Thread.sleep(10); // 添加延时以便观察
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
5.观测线程状态
package com.luo.state;
import java.util.TreeMap;
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); //Run
while(state!=Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState(); //更新线程状态
System.out.println(state); //输出状态
}
}
//一旦线程进入死亡状态,就不能再启动
}
6.线程优先级
package com.luo.state;
//相当于买彩票,优先级高,就给1000张,优先级低的给1张,优先级高的有更大概率被执行。
//测试线程的优先级
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(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY); //MaX_PRIORITY=10
t4.start();
// t5.setPriority(-1); //优先级设置为负数,报错
// t5.start();
// t6.setPriority(11); //优先级设置大于10也会报错
// t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
7.守护线程
在Java中,守护线程(Daemon Thread)是一种特殊类型的线程,它的存在并不会阻止Java虚拟机(JVM)的退出。当所有的非守护线程结束时,JVM就会自动退出,并且会杀死所有仍然存在的守护线程。
守护线程通常被用于执行一些后台任务或者提供一些服务,它们并不需要等待其他线程的完成。比如,在一个Web服务器中,守护线程可以用来接收客户端的请求并处理,而无需阻塞主线程。
要将一个线程设置为守护线程,可以使用线程对象的 setDaemon(true) 方法。守护线程的创建方式和普通线程相同,只是设置了守护状态后,线程启动后会成为守护线程。
守护线程在以下情况下会被终止:
所有的非守护线程都已经结束。
调用了守护线程的 stop() 方法(已废弃,不推荐使用)。
守护线程自己执行了 Thread.currentThread().interrupt() 方法。
需要注意的是,守护线程不能访问任何共享资源,因为它们可能在任何时候被停止,而无法保证数据的一致性。因此,在设计守护线程时,需要注意避免对共享资源的访问和修改。
总结来说,守护线程是一种后台线程,当所有的非守护线程结束时,它会自动退出。它通常用于执行一些不需要等待的任务或者提供服务。
package com.luo.state;
import javax.security.auth.login.AccountLockedException;
//测试守护线程
//上帝守护你
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); //默认flase都是用户线程
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("=============goodbye world!============="); //hello world;
}
}
8.线程同步
9.三大不安全案例
具体问题如下:
多个线程对同一个账户进行操作:在 Drawing 类中,多个线程通过修改 Account 对象的 money 字段来模拟取款操作。由于多个线程同时执行,会出现竞争条件,导致数据不一致。
判断余额和取款操作不是原子性的:在 run() 方法中,判断是否有足够的余额和更新余额的操作并没有保证原子性。即使判断为有足够的余额,其他线程也有可能在此之前修改了余额,导致实际取款时余额不足。
未进行线程同步控制:在多个线程修改共享数据时,需要进行同步控制,以避免竞争条件和数据不一致。但是上述代码中并没有使用同步机制,因此存在线程安全问题。
要解决这些问题,可以使用以下方法之一:
使用 synchronized 关键字:在 run() 方法中使用 synchronized 关键字,确保只有一个线程能够访问和修改共享数据,从而避免竞争条件和数据不一致。
使用 Lock 接口:使用 java.util.concurrent.locks.Lock 接口及其实现类,如 ReentrantLock,进行显式的加锁和释放锁操作,以实现线程同步。
使用 AtomicInteger 类:将 Account 类中的 money 字段改为 AtomicInteger 类型,它提供了原子性的自增和自减操作,避免了竞争条件和数据不一致。
package com.luo.syn;
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account=new Account(100,"结婚基金");
Drawing you=new Drawing(account,50,"你");
Drawing wife=new Drawing(account,100,"妻子");
you.start();
wife.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;
}
@Override
public void run() {
//判断有没有钱
if(account.money-drawingMoney<0)
{
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//卡内余额
account.money-=drawingMoney;
//手里的钱
nowMoney+=drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
package com.luo.syn;
//线程不安全,有负数
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) {
try {
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0) {
flag=false;
return;
}
Thread.sleep(10);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
package com.luo.syn;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list=new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(2000);
System.out.println(list.size());
}
}