class Student {
public static void main(String[] args) {
Mythread mythread=new Mythread();
Thread t2=new Thread(mythread);
t2.start();
}
}
class Mythread implements Runnable {
@Override
public void run() {
Thread t1 = Thread.currentThread();//获取当前线程对象 ,调用Thread的grt方法
System.out.println("线程id为"+t1.getId()+" 线程名字为:"+t1.getName() + " hello word");//Thread类中有getName方法
}
}
sleep方法实现时钟计时效果
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo8 {
public static void main(String[] args) {
mmm myThread = new mmm();
Thread thread = new Thread(myThread);
thread.start();
}
}
class mmm implements Runnable {
@Override
public void run() {
while (true) {
Date d1 = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));
System.out.println(sdf.format(d1));
try {
Thread.currentThread(). sleep(1000);//Thread.currentThread()获取当前线程
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
setDemao实现守护线程
public class DemoDaemon {
public static void main(String[] args) {
thread t=new thread();
t.setDaemon(true);//守护线程必须在start之前调用
t.start();
System.out.println("==============");
for (int i = 0; i < 10; i++) {
System.out.println("主线程 "+i);
}
}
}
class thread extends Thread{
@Override
public void run() {
// System.out.println( isDaemon()?"是守护线程":"不是守护线程");默认不是守护线程
for (int i = 0; i < 30; i++) {
System.out.println("子线程"+i);
}
}
}