1 多线程的实现(runnable、callable)
2 多线程的同步(锁syn,lock)
3 多线程的通讯(wait notify XX)
题目:一个线程打印0,另一个线程打印1
思路分析:
俩条线程互相唤醒,俩条线程不能同时执行,需要sync关键字
class Phone {
public static synchronized void sendSMS() throws Exception {
Thread.sleep(3000);
System.out.println("------sendSMS");
}
public synchronized void sendEmail() throws Exception {
System.out.println("------sendEmail");
}
public void getHello() {
System.out.println("------getHello");
}
}
/**
*
*
*
* 1 标准访问,先打印短信还是邮件 2 停4秒在短信方法内,先打印短信还是邮件 3 新增普通的hello方法,是先打短信还是hello 4
* 现在有两部手机,先打印短信还是邮件 5 两个静态同步方法,1部手机,先打印短信还是邮件 6 两个静态同步方法,2部手机,先打印短信还是邮件
* 7 1个静态同步方法,1个普通同步方法,1部手机,先打印短信还是邮件 8 1个静态同步方法,1个普通同步方法,2部手机,先打印短信还是邮件
* ---------------------------------
*
*/
public class Lock_8 {
public static void main(String[] args) throws Exception {
Phone phone = new Phone();
new Thread(() -> {
try {
phone.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
}, "发短信的线程").start();
Thread.sleep(1000);
new Thread(() -> {
try {
phone.getHello();
} catch (Exception e) {
e.printStackTrace();
}
}, "发邮件的线程").start();
}
}
================================================================================================
class ShareDataOne// 资源类
{
private int number = 0;// 初始值为零的一个变量
/***
* 增加方法,打印数字1
*
* @throws InterruptedException
*/
public synchronized void increment() throws InterruptedException {
// 1判断,如果是if,当线程被唤醒后,不进行判断number的数值
while (number != 0) {
this.wait();
}
// 2干活
++number;
System.out.println(Thread.currentThread().getName() + " \t" + number);
// 3通知
this.notifyAll();
}
/***
* 减少方法,打印数字0
*
* @throws InterruptedException
*/
public synchronized void decrement() throws InterruptedException {
// 1判断
while (number == 0) {
this.wait();
}
// 2干活
--number;
System.out.println(Thread.currentThread().getName() + " \t" + number);
// 3通知
this.notifyAll();
}
}
==============
public class ShareDataOneTest {
public static void main(String[] args) {
// 资源类
ShareDataOne shareDataOne = new ShareDataOne();
// new Thread(null,线程名);
// 打印0,10次
new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
shareDataOne.decrement();
} catch (Exception e) {
}
}
}, "打印0的线程1").start();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
shareDataOne.decrement();
} catch (Exception e) {
}
}
}, "打印0的线程2").start();
// 打印1,10次
new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
shareDataOne.increment();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "打印1的线程1").start();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
shareDataOne.increment();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, "打印1的线程2").start();
}
}