方法一:
(1)定义一个类Mythead类继承自Thread
(2)在Mythread类里面重写Thread的run方法
(3)在测试类里面创建Mythrea类的对象
(4)使用Mythread的对象调用start方法开启线程
代码展示
Mythread类
public class Mythread extends Thread{
public Mythread() {
}
//有了带参构造以后系统的默认无参构造就没有了我们要手动给出
public Mythread(String name) {
super(name); //我把这个name 传递给父类
}
@Override
public void run() {
for (int i = 0 ; i<200 ;i++ ){
String thname = getName();
System.out.println(thname+":"+i);
}
}
}
测试类
public static void main(String[] args) {
//创建线程对象
Mythread mythread1 = new Mythread();
Mythread mythread2 = new Mythread();
Mythread mythread3 = new Mythread();
//给线程起个名
mythread1.setName("one");
mythread2.setName("two");
mythread3.setName("three");
//获取一下线程的优先级
// System.out.println(mythread1.getPriority());
// System.out.println(mythread2.getPriority());
// System.out.println(mythread3.getPriority());
/*]
如果我们没有给线程指定优先级的话 默认的优先级是 5
*/
//获取一下优先级的范围
// System.out.println("优先级的范围");
// System.out.println("最大优先级:"+Thread.MAX_PRIORITY); //10
// System.out.println("最小优先级:"+Thread.MIN_PRIORITY); //1
// System.out.println("默认优先级:"+Thread.NORM_PRIORITY); //5
//为我们的线程设置优先级
mythread1.setPriority(4);
mythread2.setPriority(5);
mythread3.setPriority(7);
//开线程
mythread1.start();
mythread2.start();
mythread3.start();
}
方法二:
(1)定义一个类MyRunnable类实现Runnable接口
(2)在MyRunnable类里面重写Runnable的run方法
(3)在测试类里面创建MyRunnable类的对象
(4)在测试类里面创建Thread类的对象,参数是MyRunnable类的对象,并且Thread类的构造方法可以设置线程的名字
(5)使用Thread的对象调用start方法开启线程
MyRunnable类
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0 ; i< 100; i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
}
测试类
public static void main(String[] args) {
// 创建myRunnable对象
MyRunnable myRunnable = new MyRunnable();
//创建线程对象 参数是myRunnable
Thread thread1 = new Thread(myRunnable,"线程1"); //第二个参数是给线程设置名字
Thread thread2 = new Thread(myRunnable,"线程2");
//开启线程
thread1.start();
thread2.start();
}