这里不调用run()方法是因为run()方法只是普通方法,不能作为线程,start()才是线程
public class thread01 {
public static void main(String[] args) throws InterruptedException {
Cat cat = new Cat();//创建cat对象,当作线程使用
cat.start();//启动
//当main线程启动 子线程thread-0,主线程不会阻塞,会继续运行
//main线程和子线程thread-0交替运行
System.out.println("主线程"+Thread.currentThread().getName());
for (int i = 0; i < 10; i++) {
System.out.println("主线程i="+i);
Thread.sleep(1000);
}
}
}
class Cat extends Thread{
int time = 0;
public void run(){
while (true) {
//线程每隔一秒输出一次
System.out.println("喵喵" + (++time) + "线程是" + Thread.currentThread().getName());
try {
Thread.sleep(1000);//线程休眠一秒钟
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if (time == 80){
break;
}
}
}
}
为什么要用start()方法而不是run()方法
用run方法此时线程就只有main方法在走,调用完一个方法在调用下一个方法,没有启动线程,这是串行
而用start方法就会调用jvm里面的start0方法再调用run方法,这时候调用了线程,是并行的
public class thread02 {
public static void main(String[] args) {
Dog dog = new Dog();
//dog不能调用start
//创建Thread对象,把dog(实现Runnable)放入Thread
Thread thread = new Thread(dog);
thread.start();
}
}
class Dog implements Runnable{//通过实现Runnable接口,开发线程
int count = 0;
@Override
public void run() {
while (true){
System.out.println("旺旺" + (++count)+ Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
yield是由cpu来决定执行哪个线程,如果当cpu资源紧缺时候yield就会生效,优先执行指定线程,如果当cpu资源充裕时候yield不生效
join则必定会生效,优先执行指定线程
这时,main退出后,子程序也会退出
线程同步
5.非静态方法加锁
synchronized(this)+代码块
synchronized(object)+代码块
class Sell03 implements Runnable{
private int ticketNum = 100;
private boolean loop = true;
Object object = new Object();
public void sell() {
synchronized (object) {
if (ticketNum <= 0) {
System.out.println("售票结束");
loop = false;
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("窗口" + Thread.currentThread().getName() + "售出一张票"
+ "剩余票数=" + (--ticketNum));
}
}
6.静态方法加锁