Thread.sleep(100);
,可以达到先短信后邮件的目的。TimeUnit.SECONDS.sleep(4);
在短信方法里面(在phone类中的短信方法中),还是先打印短信package com.atguigu.sync;
import java.util.concurrent.TimeUnit;
class Machine {
public synchronized void sendSMS() throws Exception{
// TimeUnit.SECONDS.sleep(4);
System.out.println("----------sendSMS");
}
public synchronized void sendEmail() throws Exception{
System.out.println("----------sendEmail");
}
public void getHello(){
System.out.println("----------Hello");
}
}
public class Phone {
public static void main(String[] args) throws Exception {
Machine machine1 = new Machine();
Machine machine2 = new Machine();
new Thread(()->{
try {
machine1.sendSMS();
} catch (Exception e) {
e.printStackTrace();
}
},"AA").start();
Thread.sleep(10); //
new Thread(()->{
try {
machine2.sendEmail();
} catch (Exception e) {
e.printStackTrace();
}
},"BB").start();
}
}
private Lock lock = new ReentrantLock(boolean); //在创建对象的类里面设置锁,多个线程是否公平由boolean决定
synchronized
(隐式)和ReentrantLock
(显式)都是可重入锁Runnable接口方式和Thread类方式,无法返回线程结果。为了支持此功能,Java中提供了Callable接口。
Runnable接口和Callable接口:
package com.atguigu.sync;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
//实现Runnable接口
class MyThread1 implements Runnable{
@Override
public void run() {
}
}
class MyThread2 implements Callable{
@Override
public Integer call() throws Exception {
return 200;
}
}
public class Demo1 {
public static void main(String[] args) {
//Runnnable接口创建线程
new Thread(new MyThread1(),"AA").start();
//Callable
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread2());
//lam表达式
FutureTask<Integer> futureTask1 = new FutureTask<Integer>(()->{
return 1024;
});
}
}