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();
}
}
——————————————————————————————
synchronized用法同步锁(锁代码块)
class Service{
public void fun1(){
synchronized(this){
try{
Thread.sleep(3 * 1000);
}
catch(Exception e){
System.out.println(e);
}
System.out.println("fun1");
}
}
public void fun2(){
synchronized(this){
System.out.println("fun2");
}
}
}
class MyThread1 implements Runnable{
private Service service;
public MyThread1(Service service){
this.service = service;
}
public void run(){
service.fun1();
}
}
class MyThread1 implements Runnable{
private Service service;
public MyThread1(Service service){
this.service = service;
}
public void run(){
service.fun2();
}
}
class Test{
public static void main(String[] args){
Service service = new Service();
Thread t1 = new Thread(new MyThread1(service));
Thread t2 = new Thread(new MyThread2(service));
t1.start();
t2.start();
}
}
——————————————————
synchronized用法同步锁(锁方法)