1、什么是进程?
进程就是正在运行的程序,进程是系统分配资源的基本单位
2、什么是线程、什么是多线程?
线程是进程中的一条执行路径,也是CPU的基本调度单位。如果一个程序在同一时间执行多个线程,代表着这个程序支持多线程
多线程就是一个进程由多个线程组成,彼此间完成不同的工作(任务),同时执行,称为多线程
3、为什么使用多线程?
为了充分利用cpu,提高了程序的效率
4、java中如何创建线程的?
(1)通过继承Thread类重写run()方法来创建线程,然后通过start方法开启线程
注意: 不能直接 对象名.run() 【这是在main线程中执行该方法而不是使用新线程】
public class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i <10 ; i++) {
System.out.println(this.getName()+"============="+i);
}
}
}
public class test {
public static void main(String[] args) throws Exception{
//创建线程对象
MyThread myThread=new MyThread();
//开启线程
myThread.start();
}
}
(2)通过实现Ruable接口中的run方法,然后再new该类的对象.该类是线程任务对象
接着通过Thread类中的public Thread(Runnable target, String name)或public Thread(Runnable target)构造方法创建线程对象。其中target是线程任务对象,name是线程名
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName()+"++++++++++++++++"+i);
}
}
}
public class test {
public static void main(String[] args) throws Exception{
MyRunnable myRunnable = new MyRunnable();
Thread thread=new Thread(myRunnable,"myThread01");
thread.start();
}
}
(3)通过实现Callable接口中的V call() throws Exception;方法来,接着创建该类的对象myCallable,再创建FutureTask对象,FutureTask<V> implements RunnableFuture<V>该对象实现了RunnableFuture接口,interface RunnableFuture<V> extends Runnable, Future<V> RunnableFuture接口又继承了Runnable,Future接口。另外FutureTask类中有一个FutureTask(Callable<V> callable)构造函数,我们可以在创建FutureTask对象时将myCallabale作为参数传过去。然后创建线程对象将FutureTask对象传过去。通过线程对象开启线程。可以通过调用FutureTask中的get方法获取任务执行完返回的值
public class MyCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int sum=0;
for (int i = 0; i <=1000 ; i++) {
if(i%3==0){
sum+=i;
}
}
return sum;
}
}
public class test {
public static void main(String[] args) throws Exception{
MyCallable myCallable=new MyCallable();
FutureTask futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
Object o = futureTask.get();
System.out.println(o);
}
}
5. Runable和Callable的区别?
1.Callable有返回值,而且抛出异常。而Runnable无返回值和异常抛出
2.Callable是对Runnable的补充。
3.Runnable是JDK1.0出的而Callable是JDK1.5出的
6、Thread类中常用的方法
-
-
void
setPriority(int newPriority)设置
线程的优先级。
-
-
-
int
getPriority()获取
线程的优先级。
-
-
-
void
start()开启线程
-
-
-
static void
sleep(long millis)让当前线程睡眠(暂停)millis毫秒 millis代表毫秒数
-
-
-
void
join()让某个线程加入到正在运行的线程
-
-
-
static void
yield()让当前线程放弃cup资源重新参与到下一次cpu竞争
-
-
-
void
setDaemon(boolean on) 设置守护线程,必须在开启线程之前设置
-