线程初学

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用法同步锁(锁方法)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值