一、线程的创建方式
- 利用Thread子类创建线程
- 直接创建线程对象,然后实现Runnable接口。
①下面是一个利用线程子类创建一个简单线程的demo
CreateThread类
public class CreateThread extends Thread {
public void run(){
for(int i=0;i<10;i++){
System.out.println("No."+i);
}
}
public static void main(String args[]){
CreateThread ct = new CreateThread();
CreateThread01 ct01 = new CreateThread01();
ct.start();
ct01.start();
}
}
测试类
public class CreateThread01 {
public void run(){
for(int i=0;i<10;i++){
System.out.println("--"+i);
}
}
}
②利用Runnable创建一个线程的小demo [其中,run()方法是必须实现的方法]
public class ThreadMain {
public static void main(String arga[]){
ThreadRunnable tr1 = new ThreadRunnable();
ThreadRunnable tr2 = new ThreadRunnable();
Thread t1 = new Thread(tr1);
Thread t2 = new Thread(tr2);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
public class ThreadRunnable implements Runnable{
@Override
public void run() {
int flag = 1;
// TODO Auto-generated method stub
String name = Thread.currentThread().getName();
if(name.equals("t1")){
System.out.print("现在执行的线程是:t1");
}else{
System.out.print("现在执行的线程是:t2");
}
}
}
二、线程的简单应用
- 介绍线程中常用的sleep()方法
- 计时器线程Timer类
①利用sleep()方法,每隔一秒打印一次当前时间
构造方法:sleep(int millsecond)单位:毫秒
public class TimerMain {
public static void main(String args[]){
CountTime ct = new CountTime();
Thread t = new Thread(ct);
t.start();
}
}
public class CountTime implements Runnable{
SimpleDateFormat m = new SimpleDateFormat("hh:mm:ss");
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
Date date = new Date();
System.out.println(m.format(date));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
②让所要执行的代码过一段时间执行
(比如可以利用Timer类实现一个闹钟,每隔隔一秒获取一次系统时间,当设置时间等于系统时间,闹铃等。。。好吧,那其实是我android课上利用Timer写的一个程序)
下面这个小demo,用到类Timer类常用的schedule() 方法,下面是它的构造方法
- public void schedule(TimerTask task,long delay)
- public void schedule(TimerTask task,Date time)
- public void schedule(TimerTask task,long delay,long period)
- public void schedule(TimerTask task,Date firstTime,long period)
public class TimerMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Timer t = new Timer();
long startTime = System.currentTimeMillis();
t.schedule(new TimerTask(){
int flag = 1;
@Override
public void run() {
// TODO Auto-generated method stub
long endTime = System.currentTimeMillis();
System.out.print("过了"+String.valueOf(endTime-startTime)+"该语句开始执行");
flag=0;
if(flag==0){
t.cancel();
}
}},1000,1000);
}
}
关于对线程的学习,初学者可能觉得他没什么用,其实我学了java两年了,最近在学Android才发现线程很重要很重要的一章。我也是为此来复习线程的一些简单知识。有兴趣的人还可以看看,java有多多线程编程,其中的种种,不是我能述尽的。提供一个传送门 https://www.runoob.com/java/java-multithreading.html