线程初学

class MyThread implements Runnable{
int i = 100;
public void run(){
while(true){
synchronized(this){
//Thread.currentThread()获取当前代码在哪个线程中运行,会返回线程对象(Thread对象)
System.out.println(Thread.currentThread().getName() + i);
i--;
//让线程让出CPU,使所有线程重新竞争CPU
Thread.yield();
if(i<0)
break;
}
}
}
}

class Test{
public static void main(String[] args){
MyThread mythread = new MyThread();

//生成两个Thread对象,但是这两个Thread对象共用同一个线程体
Thread t1 = new Thread(mythread);
Thread t2 = new Thread(mythread);

//每一个名字都有名字,可以通过Thread对象的setName()方法设置线程名字
t1.setName("线程a");
t2.setName("线程b");

//分别启动两个线程
t1.start();
t2.start();
}
}

猜你喜欢

转载自317324406.iteye.com/blog/2241563