目录
currentThread()方法返回正在被执行的线程的信息。
一、继承Thread类实现多线程
线程不一定执行,cpu安排调度
在线程中主线程和分线程是一起执行的 -------调用start
调用run方法时则是有先后顺序的
package ThreadDemo1;
public class Threadstudy extends Thread{
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("分线程"+i);
}
}
public static void main(String[] args) {
Threadstudy threadstudy = new Threadstudy();
threadstudy.start();
for (int i = 0; i < 200; i++) {
System.out.println("主线程"+i);
}
}
}
二、实现Runnable接口实现多线程
Thread在源码中的定义
public
class Thread implements Runnable {
/* Make sure registerNatives is the first thing <clinit> does. */
private static native void registerNatives();
static {
registerNatives();
}
所以Thread已经实现了Runnable接口(和上面只继承Thread的方法一样):
可以避免单继承的局限性、灵活方便、方便同一个对象被多个线程使用也就是Runnable一个对象,将这个对象 可以放在不同的Thread对象里面使用;
package ThreadDemo1;
public class Runnablestudy implements Runnable{
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("分线程的学习"+i);
}
}
public static void main(String[] args) {
Runnablestudy runnablestudy = new Runnablestudy();
Thread thread = new Thread(runnablestudy);
thread.start();
for (int i = 0; i < 200; i++) {
System.out.println("多线程的学习"+i);
}
}
}
利用龟兔赛跑实现多线程的进行Runnable接口
currentThread()方法返回正在被执行的线程的信息。
package ThreadDemo1;
//龟兔赛跑实现线程
public class Runnablestudy implements Runnable{
private static String winner;
public void run(){
for (int i = 0; i <=100; i++) {
//模拟兔子休息
if(Thread.currentThread().getName().equals("兔子")&&i%10==0){
try{
//程序暂停1ms
Thread.sleep(1);
}catch(InterruptedException e){
//输出错误信息
e.printStackTrace();
}
}
boolean flag = gameOver(i);
if(flag){
break;
}
//输出谁走了多少步
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
//判断是否完成比赛
public boolean gameOver(int steps){
if(winner!=null){
return true;
}
{
if (steps >= 100) {
winner = Thread.currentThread().getName();
System.out.println("winner is" + winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Runnablestudy race = new Runnablestudy();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
三、Callable接口实现多线程