Java多线程编码
多线程一直是编写程序代码的一个核心,Java中实现方法有以下两种:
一、继承自Thread
class Mythread extends Thread
[
//方法
public void run()
{
//内容
}
//……
}
开启线程时调用start()方法。
二、实现Runnable接口
class 类名 implements Runnable{
方法1;
方法2;
…
public void run(){
// other code…
}
属性1;
属性2;
…
}
三、线程同步
多线程往往牵扯到共享资源的问题,Java中可以通过同步代码块实现。
语法格式:
synchronized(同步对象){
//需要同步的代码
}
四、售票系统模拟
/**
* @author Rollen-Holt
* */
class hello implements Runnable {
public void run() {
for (int i = 0; i < 10; ++i) {
sale();
}
}
publ