一 stop
public class Thread_04_Stop {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 创建实现类对象
Processor_03 p = new Processor_03();
Thread t1 = new Thread(p);
t1.start();
System.out.println("main结束");
try {
Thread.sleep(3000);
// 3秒之后 强制结束t1线程
// 不推荐使用,已经过时,容易导致死锁
// t1.stop();
p.isStop=true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Processor_03 implements Runnable {
// 标识符 : 是否停止线程
boolean isStop= false;
@Override
public void run() {
// 格式化对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
// 死循环
for (int i = 0; true; i++) {
// 判断是否终止线程
if (isStop) {
return;
}
try {
Thread.sleep(1000);
// // 获取当前系统时间
Date date = new Date();
System.out.println(sdf.format(date));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
二 jion
功能: 合并线程,多个线程合并为一个线程
代码:
public class Thread_01_Join {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Thread(new Processer_01());
Thread t2 = new Thread(new Processer_01());
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
try {
t1.join();// 执行到join的时候,因为是t1调用的,所以 main之后的代码,必须等t1执行完之后才能执行
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
class Processer_01 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
}
执行不唯一,其中一种结果为:
t2 : 0
t1 : 0
t1 : 1
t2 : 1
t2 : 2
t1 : 2
t1 : 3
t1 : 4
t2 : 3
t2 : 4
main : 0
main : 1
main : 2
main : 3
main : 4
三 Yield
功能:
yield:暂停当前正在执行的线程,并让其他线程执行
1 静态方法,写在哪个线程中,哪个线程让位
2 给同优先级让位,不同优先级不让位
3 只让出当前执行的时间片,下次让不让另说
yield()应该做的是让当前运行线程回到可运行状态,以允许具有相同优先级的其他线程获得运行机会。
因此,使用yield()的目的是让相同优先级的线程之间能适当的轮转执行。
但是,实际中无法保证yield()达到让步目的,因为让步的线程还有可能被线程调度程序再次选中。
结论:yield()从未导致线程转到等待/睡眠/阻塞状态。
在大多数情况下,yield()将导致线程从运行状态转到可运行状态,但有可能没有效果
例子:
public class Thread_02_Yield {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new Processor_02();
t1.start();
t1.setName("t1");
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+" : "+i);
}
}
}
class Processor_02 extends Thread{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
Thread.yield();
}
System.out.println(getName()+" : "+i);
}
}
}
四 线程同步(Synchronization)
功能:
线程同步 :
当多个线程同时操作同一个数据的时候,尤其是更改操作,为了保证数据的一致性和正确性,需要进行一定的保护
所以线程同步是一种数据安全机制
同步编译和异步编程
同步编程 : 线程之间不是独立的,相互有影响,必须一个个执行
异步编程 : 线程之间是独立的,相互没有影响
以下程序 因为同时操作了某个数据,导致结果不正确
1 可以使用 synchronized 修饰符解决
使用方式 public synchronized void m1(){} 使用synchronized的方法,不能被多个线程同时执行
比如 访问该对象中的某一个加锁的成员方法,那么该对象中所有的加锁的成员方法全部锁定,
其他线程都无法访问,只能排到等待,等待该线程执行结束,交出锁
比如访问一个类的加锁的静态方法,那么该类中所有加锁的静态方法 全部锁定
2 synchronized(){} 语句块解决
synchronized(对象){ // 这种方式是把该对象中所有加锁的成员方法和代码块锁全部锁定
同步代码;
}
synchronized(类名.class){ // 把该类中所有加锁的静态方法和代码块锁全部锁定
同步代码;
}
public class Thread_03_Synchronization {
public static void main(String[] args) {
A a=new A(10);
Thread t1=new Processor_03(a);
Thread t2=new Processor_03(a);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class A {
int i;
// 方法锁
// public synchronized void m1() {
public void m1() {
System.out.println("-----------");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 代码块锁
synchronized(this){
i++;
System.out.println(Thread.currentThread().getName() + " : " + i);
}
System.out.println("==========");
}
public A(int i) {
super();
this.i = i;
}
}
class Processor_03 extends Thread{
A a;
public Processor_03(A a){
super();
this.a=a;
}
@Override
public void run() {
a.m1();
super.run();
}
}
执行结果为:
t2 : 11
==========
t1 : 12
==========
如果不加锁,执行结果为:
t1 : 12
==========
t2 : 12
==========
五 Lock
功能:
JDK5.0提出 : 代码块锁,性能较好
又称为显式锁 , 因为 开启和关闭 都是手动的
synchronized是隐式锁,因为执行完自动解锁
代码:
public class Thread_04_Lock {
public static void main(String[] args) {
// TODO Auto-generated method stub
A1 a=new A1(10);
Thread t1=new Thread(new Processor_04(a));
Thread t2=new Thread(new Processor_04(a));
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class Processor_04 implements Runnable {
A1 a;
public Processor_04(A1 a) {
super();
this.a = a;
}
@Override
public void run() {
a.m1();
}
}
class A1{
Lock lock=new ReentrantLock();
int i;
public void m1() {
System.out.println("-----------");
// 开始加锁
lock.lock();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
i++;
System.out.println(Thread.currentThread().getName() + " : " + i);
//解锁
lock.unlock();
System.out.println("==========");
}
public A1(int i) {
super();
this.i = i;
}
}
六 定时器(Timer)
代码:
import java.text.ParseException;
public class Thread_05_Timer {
public static void main(String[] args) throws ParseException {
// TODO Auto-generated method stub
//创建定时器
Timer timer=new Timer();
//1 做什么事情
// 2 开始时间 , 可以是时间(到了指定时间开始执行),也可以是毫秒数(当前时间开始,多长时间之后开始执行)
// 3 执行的间隔时间
// 两秒之后开始执行,并且每隔1秒执行一次
// timer.schedule(new LogTimerTask(), 2000,1000);
long m = System.currentTimeMillis();
System.out.println(m);
m += 1000 * 6;
String string = "2021-10-30 00:50:00 000";
Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").parse(string);
timer.schedule(new LogTimerTask(), d, 3000);
System.out.println("----------");
}
}
//任务类
class LogTimerTask extends TimerTask{
@Override
public void run() {
// TODO Auto-generated method stub
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
System.out.println(sdf.format(new Date()));
}
}
七 死锁
概念:
死锁 : 在执行过程中,都遇到了加锁的功能,从而进入等待状态,导致大家都访问不了
1 某个线程执行完成,需要 先后 嵌套 锁定 两个对象
2 A线程 先进入第一个对象,并锁定第一个对象,在第一个对象中去嵌套访问并锁定第二个对象
3 B线程,先进入第二个对象,并锁定第二个对象,在第二个对象中去嵌套访问并锁定第一个对象
4 当A线程把第一个对象锁定之后,要去访问第二个对象的时候,
发现已经被B线程锁住了,只能等待B线程交出第二个对象的锁才能执行
5 当B线程把第二个对象锁定之后,要去访问第一个对象的时候,
发现已经被A线程锁住了,只能等待A线程交出第一个对象的锁才能执行
6 因此 导致 A和B都进入等待状态
例子:
public class Thread_06_DeadLock {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object o1 = new Object();
Object o2 = new Object();
Thread t1 = new T1(o1,o2);
Thread t2 = new Thread(new T2(o1,o2));
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class T1 extends Thread{
Object o1;
Object o2;
public T1(Object o1, Object o2) {
super();
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o1) {
System.out.println("t1已进入o1 准备进入后o2");
synchronized (o2) {
System.out.println( "t1 执行完成");
}
}
}
}
class T2 extends Thread{
Object o1;
Object o2;
public T2(Object o1, Object o2) {
super();
this.o1 = o1;
this.o2 = o2;
}
@Override
public void run() {
synchronized (o2) {
System.out.println("t2已进入o2 准备进入后o1");
synchronized (o1) {
System.out.println( "t2 执行完成");
}
}
}
}
运行结果:
t1已进入o1 准备进入后o2
t2已进入o2 准备进入后o1
程序不会结束,一直执行
八 wait
wait : 让当前线程进入等待状态 , 无参 或者传入0 都意味着 不可以自动醒,只能被唤醒,也可以传入毫秒数,到时间自动醒
notifyAll : 唤醒在当前对象中等待的所有线程
notify : 唤醒在当前对象中等待的摸一个线程
以上两个方法必须用在成员加锁的方法中
代码:
public class Thread_07_Wait {
public static void main(String[] args) {
// TODO Auto-generated method stub
Num num = new Num();
Thread t1 = new PrintOdd(num);
Thread t2 = new PrintEven(num);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class PrintOdd extends Thread {
Num num;
public PrintOdd(Num num) {
super();
this.num = num;
}
@Override
public void run() {
while (true) {
num.printOdd();
}
}
}
class PrintEven extends Thread {
Num num;
public PrintEven(Num num) {
super();
this.num = num;
}
@Override
public void run() {
while (true) {
num.printEven();
}
}
}
// 业务类
class Num {
int count = 1;
public synchronized void printOdd() {
System.out.println(Thread.currentThread().getName() + " : " + count);
count++;
// 唤醒所有在当前对象中睡眠的线程
this.notifyAll();
try {
Thread.sleep(500);
// 挂起 交出该对象持有的锁,让其他线程可以执行
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printEven() {
System.out.println(Thread.currentThread().getName() + " : " + count);
count++;
// 唤醒所有在当前对象中睡眠的线程
this.notifyAll();
try {
Thread.sleep(500);
// 挂起 交出该对象持有的锁,让其他线程可以执行
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}