一、创建线程的两种方式
1 继承runnable接口
public class threadimprunnable implements runnable
{
/**
* 线程运行时执行的方法
*/
public void run()
{
for (int i = 0; i < 500; i++)
{
system.out.println(thread.currentthread().getname() + i);
}
}
}
public class test
* 主线程,启动线程必须是start方法
public static void main(string[] args)
threadimprunnable tr = new threadimprunnable();
thread t = new thread(tr);
t.start();
2 继承thread类
public class threadextends extends thread
threadextends tr = new threadextends();
tr.start();
二、线程的一些方法
1 sleep
public class sleepthread implements runnable
try
// 该线程进入阻塞状态5秒
thread.sleep(5000);
for (int i = 0; i < 500; i++)
{
system.out.println(thread.currentthread().getname() + i);
}
catch (interruptedexception e)
// 若调用该线程的interrupt方法,会报该异常,真实程序中可以关闭一些资源
e.printstacktrace();
public class sleeptest
* 主线程
sleepthread tr = new sleepthread();
thread t = new thread(tr);
t.start();
2 join
public class jointhread implements runnable
for (int i = 0; i < 100; i++)
public class jointest
jointhread jt = new jointhread();
thread t = new thread(jt);
// 调用该方法将当前线程(此处是主线程)合并到本线程中,执行完本线程,再执行当前线程
t.join();
3 yield
public class yieldthread extends thread
if (i % 10 == 0)
// 当能被10整除时本线程让出优先级,让其他线程先执行一会,可看到t1_10下面紧接着t2的结果,同样t2_20下面紧接着t1的结果
yield();
public class yieldtest
yieldthread yt = new yieldthread();
thread t1 = new thread(yt, "t1_");
t1.start();
thread t2 = new thread(yt, "t2_");
t2.start();
4 setpriority
public class prioritythread extends thread
public class prioritytest
* 线程优先级默认是5
int norm = thread.norm_priority; // 5
int max = thread.max_priority; // 10
int min = thread.min_priority; // 1
prioritythread yt = new prioritythread();
t1.setpriority(norm + 3);