1.实现Runnable接口来创建线程
创建一个类implements Runnable
重写run()方法
public class D9 implements Runnable{
public void run() {
int n = 100;
for(int i=0;i<n;i++){
System.out.println("This is thread D9 " + i);
}
}
}
创建Thread类(用该类对象作为参数),调用start()方法
public static void main(String[] args) {
D9 d9 = new D9();
new Thread(d9).start();
int n = 100;
for(int i=0;i<n;i++){
System.out.println("This is main Thread " + i);
}
}
优点:避免单继承局限性,同一个对象可以被多个线程使用
多个线程同时去取糖果
public class D10 implements Runnable{
private int candyNum = 50;
@Override
public void run() {
while (candyNum >= 0) {
System.out.println(Thread.currentThread().getName() + " got candy " + candyNum--);
}
}
public static void main(String[] args) {
D10 d10 = new D10();
new Thread(d10).start();
new Thread(d10).start();
new Thread(d10).start();
new Thread(d10).start();
}
}
线程并发可能会导致资源分配出问题,比如两个线程都取了同一个资源,并且都认为只有自己获得了该资源
2.用多线程完成龟兔赛跑代码
public class Race implements Runnable{
private static String winner;
@Override
public void run() {
for(int i=0;i<=100;i++){
if(gameOver(i)) return;
System.out.println(Thread.currentThread().getName() + " run " + i + " miles");
}
}
public boolean gameOver(int i){
if(winner!=null) {
return true;
}else if(i>=100){
winner = Thread.currentThread().getName();
System.out.println("winner is "+ winner);
return true;
}else{
return false;
}
}
public static void main(String[] args) {
Race r = new Race();
new Thread(r, "rabbit").start();
new Thread(r,"tortoise").start();
}
}
从中领会到线程是独立存在的,由CPU调度交替运行,但都有属于线程的局部变量,工作环境