概念:
线程:程序中单独顺序的控制流
线程本身依靠程序运行
线程是程序中的顺序控制流,只能使用分配给程序的资源和环境
进程:执行中的程序
一个进制可以包含一个或多个线程
一个进程至少包含一个线程,主方法即主线程
一.使用继承Thread类:
线程的启动要用start()方法,切记用用对象调用run()方法;
可以看到结果并发执行。
public class ThreadDemo1 {
private static MyThread thread1;
private static MyThread thread2;
public static void main(String[] args) {
thread1 = new MyThread("A");
thread2 = new MyThread("B");
thread1.start();
thread2.start();
}
}
public class MyThread extends Thread {
private String name;
public MyThread(String name) {
this.name = name ;
}
public void run() {
for(int i=0;i<1000;i++){
System.out.println(this.name+" "+i);
}
super.run();
}
}
二.实现Runnable接口
因为是接口,所以使用时还需要调用Thread来使用
public class ThreadDemo1 {
private static MyRunnable thread1;
private static MyRunnable thread2;
public static void main(String[] args) {
thread1 = new MyRunnable("A");
thread2 = new MyRunnable("B");
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread2);
t1.start();
t2.start();
}
}
public class MyRunnable implements Runnable {
private String name;
public MyRunnable(String name) {
this.name = name;
}
@Override
public void run() {
for(int i=0;i<1000;i++){
System.out.println(this.name+" "+i);
}
}
}
三.线程的使用方法
取得线程名称 getName();
取得当前的线程对象 currentThread();
判断线程是否启动 isAlive();
线程的强制运行 join();
线程的休眠 sleep();
1.java中的主线程是main方法,当main方法开启其他线程后,会交替执行,当主线程结束后,JVM也不会结束,需要一直等待所有线程运行完成。
2.使用join方法可以强制其他线程执行。如给出的例子当name为C线程执 行完主线程才会执行。
3.sleep方法放到哪个线程哪个线程休眠。
4.Thread的构造方法中super(“”)会改变 Thread.currentThread().getName();的名字。
public class ThreadDemo02 implements Runnable{
String name;
public ThreadDemo02(String name) {
this.name = name;
}
public void run() {
for(int i=0;i<50;i++){
System.out.println("当前的线程对象"+":"+Thread.currentThread()+i+"name:"+name);
}
}
public static void main(String[] args) {
ThreadDemo02 rDemo01 = new ThreadDemo02("A");
ThreadDemo02 rDemo02 = new ThreadDemo02("B");
Thread thread1 = new Thread(rDemo01);
Thread thread2 = new Thread(rDemo02);
System.out.println("thread1是否启动"+":"+thread1.isAlive());
thread1.start();
System.out.println("thread1是否启动"+":"+thread1.isAlive());
thread2.start();
ThreadDemo02 rDemo03 = new ThreadDemo02("C");
Thread thread3 = new Thread(rDemo03);
thread3.start();
for(int i=0;i<50;i++){
if(i>10){
try {
thread3.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("主线程"+i);
}
}
}