线程的通信
问题:如何使用两个线程打印1-100.线程1,线程2交替打印呢?
class Number implements Runnable{
private int number = 1;
@Override
public void run() {
while (true) {
synchronized (this) {
if (number <= 100) {
notify(); //让处于wait的线程释放 notify只会释放一条线程 谁优先级高先释放谁,notifyAll释放所有线程
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + number);
number++;
try {
wait(); //线程遇到wait时 会释放锁等待其他线程进入,而sleep是不会释放锁的
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
}
}
}
public class CommunicationTest {
public static void main(String[] args) {
Number number = new Number();
Thread t1 = new Thread(number);
Thread t2 = new Thread(number);
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}
可以看到在代码中我们使用到了wait() 和 notify() 两个方法。其实还有一个notifyAll()
说明:
1.wait() 、notify()和notifyAll()三个方法必须使用在同步代码块或者同步方法中。
2.这三个方法的调用者必须是同步代码块或者同步方法的监视器,否则会发送异常
3.这三个方法是定义在Java.lang.Object类当中
面试题:wait()和sleep()的异同
相同点:二者都可以让线程处于阻塞状态
不同点:
1.被调用的范围不同,wait()只能在同步代码块或者同步方法中,sleep()可以在任何需要的场景下被调用。
2.声明的位置不同,sleep()方法声明的Thread类当中,wait()方法声明在Object类当中
3.wait()方法被调用时会释放同步监视器,而sleep()调用时不会释放同步监视器
创建线程的其他方式
1.实现Callable接口,JDK5.0新增 比Runnable更加强大
class NumThread implements Callable{
@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
return sum;
}
}
public class ThreadNew {
public static void main(String[] args) {
NumThread numThread = new NumThread();
FutureTask futureTask = new FutureTask(numThread);
new Thread(futureTask).start();
try {
Object sum = futureTask.get();
System.out.println(sum);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
如何理解实现Callable创建新线程的方式比实现Runnable接口创建新线程的方式更强大?
①call()有返回值
②call()支持抛出异常,能被外面的操作捕获
③Callable支持泛型
2.线程池
class NumberThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i%2==0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
class NumberThread1 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
if (i%2!=0){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
//设置线程池
service1.setCorePoolSize(5);
service1.execute(new NumberThread());
service1.execute(new NumberThread1());
service1.shutdown();
}
}
线程池的优点
1.提高响应速度(减少了创建新线程的时间)
2.降低资源消耗(重复利用线程池中线程,不需要每次都创建)
3.便于线程管理
可以设置下面的一些属性
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止