java-day-24

2021.10.29 晴

Join:

package study;

/**
 * Join: 合并线程,将多个线程合为一个线程
 * 
 * @author 落华见樱
 *
 */
public class Part01_Join {
	public static void main(String[] args) {
		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 {
			// 执行到join的时候,因为是t1调用的,所以 main之后的代码,必须等t1执行完之后才能执行
			t1.join();

		} catch (InterruptedException e) {
			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);
		}
	}
	
}

yield:

package study;
/**
 * yield : 暂停当前正在执行的线程,并让其他线程执行
 * 		1 静态方法,写在哪个线程中,哪个线程让位
 * 		2 给同优先级让位,不同优先级不让位
 * 		3 只让出当前执行的时间片,下次让不让另说
 * 
 * yield()应该做的是让当前运行线程回到可运行状态,以允许具有相同优先级的其他线程获得运行机会。
 * 	因此,使用yield()的目的是让相同优先级的线程之间能适当的轮转执行。
 * 但是,实际中无法保证yield()达到让步目的,因为让步的线程还有可能被线程调度程序再次选中。
 *
 *结论:yield()从未导致线程转到等待/睡眠/阻塞状态。
 *在大多数情况下,yield()将导致线程从运行状态转到可运行状态,但有可能没有效果
 * @author 落华见樱
 *
 */
public class Part02_Yield {
	public static void main(String[] args) {
		Thread t1 = new Processor_02();
		t1.start();
		
		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);
		}
	}
}

线程同步:

package study;
/**
 * 线程同步 :
 * 
 * 当多个线程同时操作同一个数据的时候,尤其是更改操作,为了保证数据的一致性和正确性,需要进行一定的保护
 * 
 * 所以线程同步是一种数据安全机制
 * 
 * 同步编译和异步编程
 * 
 * 同步编程 : 线程之间不是独立的,相互有影响,必须一个个执行
 * 
 * 异步编程 : 线程之间是独立的,相互没有影响
 * 
 * 以下程序 因为同时操作了某个数据,导致结果不正确
 * 		1 可以使用 synchronized 修饰符解决
 * 				使用方式  public synchronized void m1(){} 使用synchronized的方法,不能被多个线程同时执行
 * 				比如 访问该对象中的某一个加锁的成员方法,那么该对象中所有的加锁的成员方法全部锁定,
 * 					其他线程都无法访问,只能排到等待,等待该线程执行结束,交出锁
 * 				比如访问一个类的加锁的静态方法,那么该类中所有加锁的静态方法 全部锁定
 * 		2 synchronized(){} 语句块解决
 * 				synchronized(对象){  // 这种方式是把该对象中所有加锁的成员方法和代码块锁全部锁定
 * 					同步代码;
 * 				}
 * 				synchronized(类名.class){  // 把该类中所有加锁的静态方法和代码块锁全部锁定
 * 					同步代码;
 * 				}
 * @author 落华见樱
 *
 */
public class Part03_synchronzied {
	public static void main(String[] args) {
		A a = new A(10);
		A a1 = new A(11);
		Thread t1 = new Thread(new Processor_03(a));
		Thread t2 = new Thread(new Processor_03(a));
		t1.setName("t1");
		t2.setName("t2");
		t1.start();
		t2.start();
	}
}

class Processor_03 implements Runnable {
	A a;

	public Processor_03(A a) {
		super();
		this.a = a;
	}

	@Override
	public void run() {
		a.m1();
	}
}

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;
	}
}

Lock:

package study;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * JDK5.0提出 : 代码块锁,性能较好
 * 	又称为显式锁 , 因为 开启和关闭 都是手动的
 * 	synchronized是隐式锁,因为执行完自动解锁
 * @author 落华见樱
 *
 */
public class Part04_Lock {
	public static void main(String[] args) {

		Abc a = new Abc(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 {
	Abc a;

	public Processor_04(Abc a) {
		super();
		this.a = a;
	}

	@Override
	public void run() {
		a.m1();
	}
}

class Abc {
	int i;
	// 创建锁对象
	Lock lock = new ReentrantLock();

	public void m1() {
		System.out.println("-----------");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// synchronized (this) {
		// 开始加锁
		lock.lock();
		i++;
		System.out.println(Thread.currentThread().getName() + " : " + i);
		// 解锁
		lock.unlock();
		// }

		System.out.println("==========");

	}

	public Abc(int i) {
		super();
		this.i = i;
	}
}

Timer:

package study;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class Part05_Timer {
	public static void main(String[] args) throws ParseException {
		// 创建定时器
				Timer timer = new Timer();
				// 1 做什么事
				// 2 开始时间 , 可以是时间(到了指定时间开始执行),也可以是毫秒数(当前时间开始,多长时间之后开始执行)
				// 3 执行的间隔时间
				// 两秒之后开始执行,并且每隔1秒执行一次
				// timer.schedule(new LogTimerTask(), 2000,1000);
				long m = System.currentTimeMillis();
				m += 1000 * 60;
				String string = "2021-10-29 10:50:00 000";
				Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS").parse(string);
				timer.schedule(new LogTimerTask(), d, 1000);
				System.out.println("----------");
	}
}
class LogTimerTask extends TimerTask {
	@Override
	public void run() {
		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS")
				.format(new Date()));
	}
}

DeadLock:

package study;
/**
 * 死锁 : 在执行过程中,都遇到了加锁的功能,从而进入等待状态,导致大家都访问不了
 * 
 * 1 某个线程执行完成,需要 先后 嵌套 锁定 两个对象
 * 	2 A线程 先进入第一个对象,并锁定第一个对象,在第一个对象中去嵌套访问并锁定第二个对象
 * 3 B线程,先进入第二个对象,并锁定第二个对象,在第二个对象中去嵌套访问并锁定第一个对象
 * 	4 当A线程把第一个对象锁定之后,要去访问第二个对象的时候,
 * 			发现已经被B线程锁住了,只能等待B线程交出第二个对象的锁才能执行
 * 5 当B线程把第二个对象锁定之后,要去访问第一个对象的时候,
 * 			发现已经被A线程锁住了,只能等待A线程交出第一个对象的锁才能执行
 * 6 因此 导致 A和B都进入等待状态
 * @author 落华见樱
 *
 */
public class Part06_DeadLock {
	public static void main(String[] args) {
		Object o1 = new Object();
		Object o2 = new Object();
		Thread t1 = new T1(o1,o2);
		Thread t2 = new Thread(new T2(o1,o2));
		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 执行完成");
				}
			}
	}
}

wait:

package study;
/**
 * wait : 让当前线程进入等待状态 , 无参 或者传入0  都意味着 不可以自动醒,只能被唤醒,也可以传入毫秒数,到时间自动醒
 * notifyAll : 唤醒在当前对象中等待的所有线程
 * notify : 唤醒在当前对象中等待的摸一个线程
 * 
 * 以上两个方法必须用在成员加锁的方法中
 */
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Part07_wait {
	public static void main(String[] args) {
		Num num=new Num();
		Thread a1=new Thread(new A1(num));
		Thread a2=new Thread(new A2(num));
		a1.start();
		a2.start();
	}
}

class A1 implements Runnable {
	Num num;

	public A1(Num num){
		this.num=num;
	}
	
	@Override
	public void run() {
		while(true){
			num.m1();
		}		
	}

}

class A2 implements Runnable {
	Num num;

	public A2(Num num){
		this.num=num;
	}
	
	@Override
	public void run() {
		while(true){
	        num.m2();
		}
	}
}

class Num {
	int count = 0;

	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss  SSS");

	public synchronized void m1() {
		Date date=new Date();
		String canshu=sdf.format(date);
		System.out.println(canshu);
		System.out.println("a1:" + count);
		count++;
		try {
			// 唤醒所有在当前对象中睡眠的线程
			this.notifyAll();
			Thread.sleep(500);
			// 挂起 交出该对象持有的锁,让其他线程可以执行
			this.wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public synchronized void m2() {
		Date date=new Date();
		String canshu=sdf.format(date);
		System.out.println(canshu);
		System.out.println("a2:" + count);
		count++;
		try {
			// 唤醒所有在当前对象中睡眠的线程
			this.notifyAll();
			Thread.sleep(500);
			// 挂起 交出该对象持有的锁,让其他线程可以执行
			this.wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值