一.程序,进程,线程
程序(program)是为完成特定任务、用某种语言编写的一组指令的集合。即指一 段静态的代码.
进程((process)正在内存中运行的应用程序,如运行中的QQ,运行中的音乐播 放器。进程是操作系统进行资源分配的最小单位.
线程(thread)进程可进一步细化为线程,是一个进程内部的最小执行单元,是操 作系统进行任务调度的最小单元,隶属于进程
二.创建线程
继承Thread类的方式
public class DemoThread1 {
public static void main(String[] args) {
Thread t = new MyThread();
t.start();
for (int i = 0; i < 1000000; i++) {
System.out.println("main" + i);
}
}
}
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 10000000; i++) {
System.out.println("Thread" + i);
}
}
}
实现Runnable接口的方式
public class main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable);
t.start();
for (int i = 0; i < 10000; i++) {
System.out.println("main" + i);
}
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println("Runnable" + i);
}
}
}
三.Thread类中方法
1.Java用Thread
对象表示一个线程,通过调用start()
启动一个新线程;
2.线程的执行代码写在run()
方法中;
3.Thread 中间构造方法 new Thread(Runnable task, String name) 可以给线程起个名字
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable,"xiaoming");
t.start();
也可以通过
t.getName();
t.setName();
上述两个方法获取和命名线程
4. t.join();方法 指等待t线程结束然后在继续执行自身线程
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable,"xiaoming");
t.start();
// join等待线程终止
try {
t.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 10000; i++) {
System.out.println("main" + i);
}
}
5.Thread.sleep(long millis);强迫当前线程暂停一段时间:
public class main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t = new Thread(runnable,"xiaoming");
t.start();
// Thread.sleep强迫当前线程暂停一段时间:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for (int i = 0; i < 10000; i++) {
System.out.println("main" + i);
}
}
}
6.setPriority(int newPriority);
getPriority();
设置和获取优先级
public class Main {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable, "xiaoming");
Thread t2 = new Thread(runnable, "xiaohong");
t1.setPriority(6);
t2.setPriority(4);
System.out.println(t1.getName() + t1.getPriority());
System.out.println(t2.getName() + t2.getPriority());
}
}
7.Thread currentThread();返回对当前正在执行的线程对象的引用
public class Main {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable, "xiaoming");
Thread t2 = new Thread(runnable, "xiaohong");
t1.start();
t2.start();
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
}