进程和线程的关系
正在运行的程序称之为进程,进程是系统分配资源的基本单位
线程又称轻量级进程,线程是进程中的一条执行路径
多个线程同时执行就称为多线
创建线程的方式
第一种:继承Thread类
//创建一个线程类
public class Thread extends Thread{
//run表示线程启动后执行的业务代码
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(i);
}
}
}
public class Test {
public static void main(String[] args) {
//创建线程对象
Thread t=new Thread();
//开启线程--硬件底层调用线程的run方法
t.start();
for (int i = 0; i < 20; i++) {
System.out.println("test"+i);
}
}
}
第二种:实现Runnable接口
public class Runnable implements Runnable{
@Override
public void run() {
//线程执行时的任务代码
for (int i = 0; i < 20; i++) {
System.out.println(i);
}
}
}
public class Test {
public static void main(String[] args) {
//创建线程任务对象
Runnable r=new Runnable();
//创建线程对象
Thread t=new Thread(r,"线程名");
t.start();
for (int i = 0; i < 20; i++) {
System.out.println("main"+i);
}
}
}
第三种:实现Callable接口
public class Callable implements Callable<返回类型> {
//call表示线程的任务代码.
@Override
public 返回类型 call() throws Exception {
int sum=0;
for (int i = 0; i <=100 ; i++) {
sum+=i;
}
return sum;
}
}
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable c=new Callable();
//把call对象封装到FutureTask类中 而且任务执行的结果也在FutureTask
FutureTask ft=new FutureTask(c);
Thread t=new Thread(ft);
t.start();
Object o = task.get();
System.out.println(o);
}
}
Thread的一些常用方法
start --开启线程
Thread.currentThread --获取当前线程对象
getName --获取线程名称
setName --线程命名
sleep --线程休眠
yield --当前线程让出本次执行
join --加入当前线程
setDaemon() --设置线程为守护线
//一、start
public static void main(String[] args) throws InterruptedException {
Thread t=new Thread();
t.start();
for (int i = 0; i <20 ; i++) {
System.out.println(i);
}
}
//二、Thread.currentThread this效果相同
public void run() {
for (int i = 0; i <20 ; i++) { System.out.println(Thread.currentThread());
}
}
//三、getName
public void run() {
for (int i = 0; i <20 ; i++) { System.out.println(Thread.currentThread().getName());
}
}
//四、setName
public static void main(String[] args) throws InterruptedException {
Thread t=new Thread();
t.setName("线程A");//设置线程t的名字为线程A
}
//五、sleep
public void run() {
for (int i = 0; i <20 ; i++) {
try {
Thread.sleep(1000); //延迟一秒后执行
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(i);
}
}
//六、yield 线程交换执行频率会变高
public void run() {
for (int i = 0; i <20 ; i++) {
System.out.println(i);
Thread.yield(); //当前线程让出cpu参与下次的竞争。
System.out.println("让出后再次执行代码从这里执行");
}
}
//七、join 插入的线程执行完毕才会执行当前线程
public static void main(String[] args) throws InterruptedException {
Thread t1=new Thread();
t1.setName("线程1");
Thread2 t2=new Thread2();
t2.setName("线程2");
t1.start();
t2.start();
t1.join(); //t1加入main,main需要等t1执行完才会执行。
for (int i = 0; i <20 ; i++) {
Thread.sleep(10);
System.out.println("main"+i);
}
}
//八、setDaemon 所有线程执行完毕守护线程就会停止执行
public static void main(String[] args) throws InterruptedException {
Thread t=new Thread();
t.setDaemon(true);//设置守护线程
t.start();
for (int i = 0; i <20 ; i++) {
System.out.println(i);
}
}


被折叠的 条评论
为什么被折叠?



