线程的创建有三种方式, 第一种是继承Thread类并重写run方法
public class ThreadDemo01 {
public static void main(String[] args) {
Thread t1 = new MyThread1();
Thread t2 = new MyThread2();
t1.start();
t2.start();
}
}
class MyThread1 extends Thread{
public void run(){
for(int i=0;i<100;i++){
System.out.println("1111");
}
}
}
class MyThread2 extends Thread{
public void run(){
for(int i=0;i<100;i++){
System.out.println("222222");
}
}
}
1、当前线程重写run方法定义该线程要完成的工作。这就导致了任务是定义在线程内部的,于是线程与任务有一个强耦合关系,不利于线程的重用。
2、由于JAVA是单继承的,这也导致了若继承了Thread类就无法继承其他类,在实际开发中经常会出现继承冲突的问题。
启动线程不要直接调用run方法,而是应该调用start方法,这样线程才会并发运行,run方法会在线程启动后自动被调用。
第二种创建线程的方法是:实现Runnable接口来单独定义线程任务。
public class ThreadDemo02 {
public static void main(String[] args) {
MyRunnable1 run1 = new MyRunnable1();
Runnable run2 = new MyRunnable2();
Thread t1 = new Thread(run1);
Thread t2= new Thread(run2);
t2.start();
t1.start();
}
}
class MyRunnable1 implements Runnable{
public void run(){
for(int i=0;i<10;i++){
System.out.println(11111);
}
}
}
class MyRunnable2 implements Runnable{
public void run(){
for(int i=0;i<10;i++){
System.out.println(2222);
}
}
}
第三种方法就是把第一、二种方法用匿名内部类的方式来创建:
public class ThreadDemo03 {
public static void main(String[] args) {
Thread t1 = new Thread(){
public void run(){
for(int i=0;i<10;i++){
System.out.println(11111);
}
}
};
Thread t2 = new Thread(new Runnable(){
public void run(){
for(int i=0;i<10;i++){
System.out.println(33333);
}
}
});
t1.start();
t2.start();
}
}
线程对线程的调度工作是不可控的,这主要体现在:
1、不能主动获取cpu时间片,只能被动分配。
2、时间片的长短也不是由线程决定。
在线程优先级相同的情况下,线程调度会尽可能的均匀的把时间片分配给每个线程,理论上,线程优先级高的线程获取CPU时间片的次数就多。