java c# 线程_C#转Java之路之一:线程

Java实现多线程方式有以下两种:

public class HelloWordThread implements Runnable{

public void run(){

System.out.println("HelloWordThread.run()");

System.out.println("threadName:"+Thread.currentThread().getName());

System.out.println("threadState:"+Thread.currentThread().getState());

}

}

public class CounterThread extends Thread {

@Override

public void run(){

System.out.println("threadName:"+Thread.currentThread().getName());

System.out.println("threadState:"+Thread.currentThread().getState());

}

}

线程并发保证数据一致性的关键字:synchronized

可以加在对象的方法上:

public class Counter {

private int counter=0;

public synchronized void incr() {

this.counter++;

}

public synchronized int get() {

return this.counter;

}

}

或者

public class Counter {

private int counter=0;

public void incr() {

synchronized(this){

this.counter++;

}

}

public int get() {

synchronized(this){

return this.counter;

}

}

}

切记 synchronized同步的对象是当前对象。

保证同步的同时,就会有资源消耗,java提供了一个轻量级的关键字:volatile

PS:其他对线程对象的实现方法:start、sleep、join等与C#基本一致。

关于interrupt方法:

1、此方法不会中断线程,只是一个协调机制。设置一个线程中断标志位。具体什么时候中断,线程会参考这个标志位。

所以当不知道线程在做什么事时,不能贸然调用此方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值