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(同步对象){
//需要同步的代码
}
四、售票系统模拟
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33/** * @author Rollen-Holt * */ class hello implements Runnable { public void run() { for (int i = 0; i < 10; ++i) { sale(); } } public synchronized void sale() { if (count > 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count--); } } public static void main(String[] args) { hello he = new hello(); Thread h1 = new Thread(he); Thread h2 = new Thread(he); Thread h3 = new Thread(he); h1.start(); h2.start(); h3.start(); } private int count = 5; }
最后
以上就是害羞石头最近收集整理的关于Java多线程编码Java多线程编码的全部内容,更多相关Java多线程编码Java多线程编码内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复