/**
* 创建线程的方式三:实现Callable接口,-----jdk5.0接口
* 1,创建一个实现callble的实现类
* 2,实现call方法,将此线程需要执行的操作声明在call()中
* 3,创建实现类的的对象
* 4,将此对象作为传递的参数放到TutureTask构造器中,创建TutureTask的对象
* 5,将TutureTask的对象作为参数传递到Thread类的构造器中,创建Thread对象,调用start()
*
* 如何理解Callable接口比实现runnable接口创建多线程的方式强大?
* 1,call()可以有返回值,可以抛出异常,获取异常信息
* 2,Callable支持泛型
* * @author rieson
* @create 2020-12-23-11:52
*/
class A implements Callable{
@Override
public Object call() throws Exception {
int sum=0;
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0) {
System.out.println(i);
sum +=i;
}
}
return sum;
}
}
public class CallbleTest {
public static void main(String[] args) {
A a = new A();
FutureTask futureTask = new FutureTask(a);
new Thread(futureTask).start();
try {
//get()返回值即为FutureTask构造器Callable实现重写的call()方法的返回值
Object o = futureTask.get();
System.out.println(o );
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
/**
* 创建线程的第四种方式:使用线程池
* 好处:
* 1,提高响应速度
* 2,降低资源消耗
* 3,便于线程管理,
*
* @author rieson
* @create 2020-12-23-12:36
*/
class NumberThread implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if(i%2==0){
System.out.println(i
);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1,提供指定线程数量的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
ThreadPoolExecutor service = (ThreadPoolExecutor)executorService;
service.setCorePoolSize(15);
// System.out.println(executorService.getClass());
//2,执行指定的线程操作,需要提供Runnable,callable接口实现类的对象
executorService.execute(new NumberThread());//适合使用于Runnable
//3,关闭线程池
executorService.shutdown();
// executorService.submit()//适合适用于callable
}
}
/**
* 线程通信的例子:使用两个线程打印1-100,线程一,线程二,交替打印
*
* 涉及到的三个方法:
* wait():一旦执行此方法,线程进入阻塞状态
* notify():一旦执行此方法,就会唤醒wait()的线程,唤醒一个优先级高的线程
* notifyAll():同上,唤醒所有线程
* 说明:
* 1,这些方法的调用必须使用在同步代码块中
* 2,三个方法的调用者,必须是同步代码块中的同步监视器
*
* 面试题:sleep(),wait()方法有什么异同?
* 相同点:一旦执行方法都会使线程进入阻塞状态
* 不同点:1,两个方法生命的位置不同:Thread类中声明的sleep(),Object类中声明的wait()方法
* 2,调用的不同,sleep()可以在任何场景使用,wait()只能在同步代码块中使用
* 3,关于释放同步监视器:如果两个方法在同步代码块中,sleep()自动释放,wait(),需要调用notify()方法释放
*
*
* @author rieson
* @create 2020-12-23-10:32
*/
class Number implements Runnable {
private int number = 1;
@Override
public void run() {
while (true) {
synchronized (this) {
notify();
if (number <= 100) {
System.out.println(Thread.currentThread().getName() + "" + number);
number++;
try {
//使得调用此方法的线程进入阻塞
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
break;
}
}
}
}
}
public class CommunicationTest {
public static void main(String[] args) {
Number number = new Number();
Thread thread1 = new Thread(number);
Thread thread2 = new Thread(number);
thread1.setName("线程一:");
thread2.setName("线程二:");
thread1.start();
thread2.start();
}
}
Java多线程学习补充
最新推荐文章于 2023-03-05 16:47:01 发布