多线程就不说了,很好理解,同步就要说一下了。同步,指两个或两个以上随时间变化的量在变化过程中保持一定的相对关系。所以同步的关键是多个线程对象竞争同一个共享资源。
同步分为外同步和内同步。外同步就是在外部创建共享资源,然后传递到线程中。代码如下:
- class MyThread implements java.lang.Runnable {
- private int threadId;
- private Object obj;
- public MyThread(int id, Object obj) {
- this.threadId = id;
- this.obj = obj;
- }
- @Override
- public void run() {
- synchronized (obj) { //实现obj同步
- for (int i = 0; i < 100; ++i) {
- System.out.println("Thread ID: " + this.threadId + " : " + i);
- }
- }
- }
- }
- public class TestThread {
- public static void main(String[] args) throws InterruptedException {
- Object obj = new Object();
- for (int i = 0; i < 10; ++i) {
- new Thread(new MyThread(i, obj)).start();//obj为外部共享资源
- }
- }
- }
代码如下:
- class MyThread implements java.lang.Runnable {
- private int threadId;
- private static Object obj = new Object();
- public MyThread(int id) {
- this.threadId = id;
- }
- @Override
- public void run() {
- synchronized (obj) {
- for (int i = 0; i < 100; ++i) {
- System.out.println("Thread ID: " + this.threadId + " : " + i);
- }
- }
- }
- }
- public class TestThread {
- public static void main(String[] args) throws InterruptedException {
- for (int i = 0; i < 10; ++i) {
- new Thread(new MyThread(i)).start();
- }
- }
- }