线程——显示线程名称getName和setName运用
采用两种方式一个采用继承类,一个采用实现接口
一采用继承类步骤
1在类中run方法中写
System.out.println( Thread.currentThread().getName()+"在执行");
2在主程序中应用,先new一个类,在setName传递过去参数,最后start
Xc3 xc31=new Xc3();
xc31.setName("线程1");
xc31.start();
二采用实现接口方式
Thread xc2 = new Thread(new Xc42());//线程默认级别是5
xc2.setPriority(Thread.NORM_PRIORITY + 3); //,设置线程优先级,数字越大优先级越高,优先级不是先将执行完,只是略占优
xc1.start();
继承类,显示线程名称案例
class Xc3 extends Thread
{
public void run()
{
System.out.println( Thread.currentThread().getName()+"在执行");
} //Thread.currentThread().getName表示显示当前线程名称
}
public class l63
{
public static void main(String[] args)
{
Xc3 xc31=new Xc3();
xc31.setName("线程1");
xc31.start();
Xc3 xc32=new Xc3();
xc32.setName("线程2");
xc32.start();
Xc3 xc33=new Xc3();
xc33.setName("线程3");
xc33.start();
System.out.println( Thread.currentThread().getName()+"在执行"); //主程序,main在执行
}
}
public class L64 {
public static void main(String[] args)
{
Thread xc1 = new Thread(new Xc41());
Thread xc2 = new Thread(new Xc42());//线程默认级别是5
xc2.setPriority(Thread.NORM_PRIORITY + 3); //,设置线程优先级,数字越大优先级越高,优先级不是先将执行完,只是略占优
xc1.start();
xc2.start();
}
}
实现接口,优先级
public class L64 {
public static void main(String[] args)
{
Thread xc1 = new Thread(new Xc41());
Thread xc2 = new Thread(new Xc42());//线程默认级别是5
xc2.setPriority(Thread.NORM_PRIORITY + 3); //,设置线程优先级,数字越大优先级越高,优先级不是先将执行完,只是略占优
xc1.start();
xc2.start();
}
}
class Xc41 implements Runnable {
public void run() {
for(int i=0; i<100; i++) {
System.out.println("1线程" + i);
}
}
}
class Xc42 implements Runnable {
public void run() {
for(int i=0; i<100; i++) {
System.out.println("第2个线程正在被执行: " + i);
}
}
}