什么是线程?
进程是系统分配资源的最小单位,线程是系统调度的最小单位。一个进程内的线程之间是可以共享资源的。
每个进程至少有一个线程存在,即主线程。
创建线程
方法一:可以通过继承 Thread 来创建一个线程类,该方法的好处是 this 代表的就是当前线程,不需要通过Thread.currentThread() 来获取当前线程的引用。
class MyThread extends Thread{
@Override
public void run() {
System.out.println("in MyThread");
}
}
public class CreateThread {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
方法二:创建线程-方法2-实现 Runnable 接口
通过实现 Runnable 接口,并且调用 Thread 的构造方法时将 Runnable 对象作为 target 参数传入来创建线程对象。该方法的好处是可以规避类的单继承的限制;但需要通过 Thread.currentThread() 来获取当前线程的引用。
class MyRunner implements Runnable{
@Override
public void run() {
System.out.println("in MyRunner");
}
}
public class CreateThread {
public static void main(String[] args) {
MyRunner r = new MyRunner();
Thread t = new Thread(r);
t.start();
}
}
创建10个线程,打印编号
package package1125;
public class Sequence {
public static void main(String[] args) {
//创建十个线程,打印编号
for (int i = 0; i < 10; i++) {
final int j = i;
Runnable r = new Runnable() {
@Override
public void run() {
System.out.print(j + " ");
}
};
Thread t = new Thread(r);
t.start();
}
}
}
0 1 3 2 4 6 8 9 5 7
为什么是无序的?
线程是cpu调度的最小单位
start()方法是启动线程,而run()方法只是执行任务的部分代码,不会真实启动线程.
参数的小小补充
public class CreateThread2 {
public static void main(String[] args) {
for (int i = 0;i < 10;i++){
MyThread2 thread2 = new MyThread2(i);
thread2.start();
}
}
}
class MyThread2 extends Thread{
private int i;
public MyThread2(int i){
this.i = i;
}
@Override
public void run() {
System.out.print(i);
}
}
0213456798
public class CreateThread2 {
public static void main(String[] args) {
int num = 10;
MyRunner2 myRunner2 = new MyRunner2(num);
for (int i = 0; i < 10; i++) {
Thread thread2 = new Thread(myRunner2);
thread2.start();
}
}
}
class MyRunner2 implements Runnable{
private int i ;
public MyRunner2(int i){
this.i = i;
}
@Override
public void run() {
System.out.print(i + " ");
}
}
10 10 10 10 10 10 10 10 10 10
sleep
package package1125;
public class Sequence {
public static void main(String[] args) {
//创建十个线程,打印编号
for (int i = 0; i < 10; i++) {
final int j = i;
Runnable r = new Runnable() {
@Override
public void run() {
System.out.print(j + "");
}
};
Thread t = new Thread(r);
t.start();
}
}
}
0123568974 不sleep
0 1 2 3 4 5 6 7 8 9 sleep
通过一个sleep,我终于知道线程是咋么回事,下标为i的线程打印i,但是它们的都是同级别的呀,所以start的时候,没有顺序的都打印出来了,这个时候我加了sleep睡眠,下标为i的线程睡眠i*1000,这样下标为0的线程就冒了出来,紧接着一秒过后,下标为1的线程醒来了打印1,过了两秒,下标为2的线程醒来打印2,依次打印.