当前位置:天才代写 > tutorial > JAVA 教程 > Java多线程及同步实现道理

Java多线程及同步实现道理

2017-11-12 08:00 星期日 所属: JAVA 教程 浏览:384

副标题#e#

一. 实现多线程

1. 虚假的多线程

例1:

public class TestThread
{
  int i=0, j=0;
  public void go(int flag)
  {
   while(true)
   {
    try{ Thread.sleep(100);
   }
   catch(InterruptedException e)
   {
    System.out.println("Interrupted");
   }
   if(flag==0) i++;
   System.out.println("i=" + i);
   }
   else
   {
    j++;
    System.out.println("j=" + j);
   }
  }
}
public static void main(String[] args)
{
  new TestThread().go(0);
  new TestThread().go(1);
}
}

上面措施的运行功效为:

i=1

i=2

i=3

。。。

功效将一直打印出I的值。我们的意图是当在while轮回中挪用sleep()时,另一个线程就将起动,打印出j的值,但功效却并不是这样。关于sleep()为什么不会呈现我们预想的功效,在下面将讲到。

2. 实现多线程

通过担任class Thread或实现Runnable接口,我们可以实现多线程

2.1 通过担任class Thread实现多线程

class Thread中有两个最重要的函数run()和start()。

1) run()函数必需举办覆写,把要在多个线程中并行处理惩罚的代码放到这个函数中。

2) 固然run()函数实现了多个线程的并行处理惩罚,但我们不能直接挪用run()函数,而是通过挪用start()函数来挪用run()函数。在挪用start()的时候,start()函数会首先举办与多线程相关的初始化(这也是为什么不能直接挪用run()函数的原因),然后再挪用run()函数。

例2:

public class TestThread extends Thread
{
  private static int threadCount = 0;
  private int threadNum = ++threadCount;
  private int i = 5;
  public void run()
  {
   while(true)
   {
    try
    {
     Thread.sleep(100); 
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
    System.out.println("Thread " + threadNum + " = " + i);
    if(--i==0) return;
   }
  }
  public static void main(String[] args)
  {
   for(int i=0; i<5; i++)
    new TestThread().start();
  }
}

运行功效为:

Thread 1 = 5

Thread 2 = 5

Thread 3 = 5

Thread 4 = 5

Thread 5 = 5

Thread 1 = 4

Thread 2 = 4

Thread 3 = 4

Thread 4 = 4

Thread 1 = 3

Thread 2 = 3

Thread 5 = 4

Thread 3 = 3

Thread 4 = 3

Thread 1 = 2

Thread 2 = 2

Thread 5 = 3

Thread 3 = 2

Thread 4 = 2

Thread 1 = 1

Thread 2 = 1

Thread 5 = 2

Thread 3 = 1

Thread 4 = 1

Thread 5 = 1

从功效可见,例2能实现多线程的并行处理惩罚。

**:在上面的例子中,我们只用new发生Thread工具,并没有用reference来记录所发生的Thread工具。按照垃圾接纳机制,当一个工具没有被reference引用时,它将被接纳。可是垃圾接纳机制对Thread工具“不创立”。因为每一个Thread城市举办注册行动,所以纵然我们在发生Thread工具时没有指定一个reference指向这个工具,实际上也会在某个处所有个指向该工具的reference,所以垃圾接纳器无法接纳它们。


#p#副标题#e#

3) 通过Thread的子类发生的线程工具是差异工具的线程

class TestSynchronized extends Thread
{
  public TestSynchronized(String name)
  {
   super(name);
  }
  public synchronized static void prt()
  {
   for(int i=10; i<20; i++)
   {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
  public synchronized void run()
  {
   for(int i=0; i<3; i++)
   {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
}
  public class TestThread
  {
   public static void main(String[] args)
   {
    TestSynchronized t1 = new TestSynchronized("t1");
    TestSynchronized t2 = new TestSynchronized("t2");
    t1.start();
    t1.start(); //(1)
    //t2.start(); (2) }}

运行功效为:

t1 : 0

t1 : 1

t1 : 2

t1 : 0

t1 : 1

t1 : 2

由于是同一个工具启动的差异线程,所以run()函数实现了synchronized。假如去掉(2)的注释,把代码(1)注释掉,功效将变为:

t1 : 0

t2 : 0

t1 : 1

t2 : 1

t1 : 2

t2 : 2

由于t1和t2是两个工具,所以它们所启动的线程可同时会见run()函数。

#p#副标题#e#

2.2 通过实现Runnable接话柄现多线程

假如有一个类,它已担任了某个类,又想实现多线程,那就可以通过实现Runnable接口来实现。

1) Runnable接口只有一个run()函数。

#p#分页标题#e#

2) 把一个实现了Runnable接口的工具作为参数发生一个Thread工具,再挪用Thread工具的start()函数就可执行并行操纵。假如在发生一个Thread工具时以一个Runnable接口的实现类的工具作为参数,那么在挪用start()函数时,start()会挪用Runnable接口的实现类中的run()函数。

例3.1:

public class TestThread implements Runnable
{
  private static int threadCount = 0;
  private int threadNum = ++threadCount;
  private int i = 5;
  public void run()
  {
   while(true)
   {
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
    System.out.println("Thread " + threadNum + " = " + i);
    if(--i==0) return;
   }
  }
  public static void main(String[] args)
  {
   for(int i=0; i<5; i++) new Thread(new TestThread()).start(); //(1)
  }
}

运行功效为:

Thread 1 = 5

Thread 2 = 5

Thread 3 = 5

Thread 4 = 5

Thread 5 = 5

Thread 1 = 4

Thread 2 = 4

Thread 3 = 4

Thread 4 = 4

Thread 4 = 3

Thread 5 = 4

Thread 1 = 3

Thread 2 = 3

Thread 3 = 3

Thread 4 = 2

Thread 5 = 3

Thread 1 = 2

Thread 2 = 2

Thread 3 = 2

Thread 4 = 1

Thread 5 = 2

Thread 1 = 1

Thread 2 = 1

Thread 3 = 1

Thread 5 = 1

例3是对例2的修改,它通过实现Runnable接口来实现并行处理惩罚。代码(1)处可见,要挪用TestThread中的并行操纵部门,要把一个TestThread工具作为参数来发生Thread工具,再挪用Thread工具的start()函数。

#p#副标题#e#

3) 同一个实现了Runnable接口的工具作为参数发生的所有Thread工具是同一工具下的线程。

例3.2:

package mypackage1;
public class TestThread implements Runnable
{
  public synchronized void run()
  {
   for(int i=0; i<5; i++)
   {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
  public static void main(String[] args)
  {
   TestThread testThread = new TestThread();
   for(int i=0; i<5; i++)
   //new Thread(testThread, "t" + i).start(); (1)
   new Thread(new TestThread(), "t" + i).start(); (2) }}

运行功效为:

t0 : 0

t1 : 0

t2 : 0

t3 : 0

t4 : 0

t0 : 1

t1 : 1

t2 : 1

t3 : 1

t4 : 1

t0 : 2

t1 : 2

t2 : 2

t3 : 2

t4 : 2

t0 : 3

t1 : 3

t2 : 3

t3 : 3

t4 : 3

t0 : 4

t1 : 4

t2 : 4

t3 : 4

t4 : 4

由于代码(2)每次都是用一个新的TestThread工具来发生Thread工具的,所以发生出来的Thread工具是差异工具的线程,所以所有Thread工具都可同时会见run()函数。假如注释掉代码(2),并去掉代码(1)的注释,功效为:

t0 : 0

t0 : 1

t0 : 2

t0 : 3

t0 : 4

t1 : 0

t1 : 1

t1 : 2

t1 : 3

t1 : 4

t2 : 0

t2 : 1

t2 : 2

t2 : 3

t2 : 4

t3 : 0

t3 : 1

t3 : 2

t3 : 3

t3 : 4

t4 : 0

t4 : 1

t4 : 2

t4 : 3

t4 : 4

由于代码(1)中每次都是用同一个TestThread工具来发生Thread工具的,所以发生出来的Thread工具是同一个工具的线程,所以实现run()函数的同步。

#p#副标题#e#

二. 共享资源的同步

1. 同步的须要性

例4:

class Seq
{
  private static int number = 0;
  private static Seq seq = new Seq();
  private Seq() {}
  public static Seq getInstance()
  {
   return seq;
  }
  public int get()
  {
   number++;  
   //(a)
   return number; 
   //(b)
  }
}
public class TestThread
{
  public static void main(String[] args)
  {
   Seq.getInstance().get(); 
   //(1)
   Seq.getInstance().get(); 
   //(2)
  }
}

上面是一个取得序列号的单例模式的例子,但挪用get()时,大概会发生两个沟通的序列号:

#p#分页标题#e#

今世码(1)和(2)都试图挪用get()取得一个独一的序列。今世码(1)执行完代码(a),正要执行代码(b)时,它被间断了并开始执行代码(2)。一旦今世码(2)执行完(a)而代码(1)还未执行代码(b),那么代码(1)和代码(2)就将获得沟通的值。

2. 通过synchronized实现资源同步

2.1 锁符号

2.1.1 每个工具都有一个符号锁。当工具的一个线程会见了工具的某个synchronized数据(包罗函数)时,这个工具就将被“上锁”,所以被声明为synchronized的数据(包罗函数)都不能被挪用(因为当前线程取走了工具的“锁符号”)。只有当前线程会见完它要会见的synchronized数据,释放“锁符号”后,同一个工具的其它线程才气会见synchronized数据。

2.1.2 每个class也有一个“锁符号”。对付synchronized static数据(包罗函数)可以在整个class下举办锁定,制止static数据的同时会见。

例5:

class Seq
{
  private static int number = 0;
  private static Seq seq = new Seq();
  private Seq() {}
  public static Seq getInstance(){ return seq; }
  public synchronized int get()
  {
   //(1)
   number++;
   return number;
  }
}

例5在例4的基本上,把get()函数声明为synchronized,那么在同一个工具中,就只能有一个线程挪用get()函数,所以每个线程取得的number值就是独一的了。

#p#副标题#e#

例6:

class Seq
{
  private static int number = 0;
  private static Seq seq = null;
  private Seq() {}
  synchronized public static Seq getInstance()
  {
   //(1)
   if(seq==null) seq = new Seq();
   return seq;
  }
  public synchronized int get()
  {
   number++;
   return number;
  }
}

例6把getInstance()函数声明为synchronized,那样就担保通过getInstance()获得的是同一个seq工具。

2.2 non-static的synchronized数据只能在同一个工具的纯种实现同步会见,差异工具的线程仍可同时会见。

例7:

class TestSynchronized implements Runnable
{
  public synchronized void run()
  {
   //(1)
   for(int i=0; i<10; i++)
   {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    /*(2)*/
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
}
public class TestThread
{
  public static void main(String[] args)
  {
   TestSynchronized r1 = new TestSynchronized();
   TestSynchronized r2 = new TestSynchronized();
   Thread t1 = new Thread(r1, "t1");
   Thread t2 = new Thread(r2, "t2"); //(3) //
   Thread t2 = new Thread(r1, "t2"); (4)
   t1.start();
   t2.start();
  }
}

运行功效为:

t1 : 0

t2 : 0

t1 : 1

t2 : 1

t1 : 2

t2 : 2

t1 : 3

t2 : 3

t1 : 4

t2 : 4

t1 : 5

t2 : 5

t1 : 6

t2 : 6

t1 : 7

t2 : 7

t1 : 8

t2 : 8

t1 : 9

t2 : 9

#p#副标题#e#

固然我们在代码(1)中把run()函数声明为synchronized,但由于t1、t2是两个工具(r1、r2)的线程,而run()函数是non-static的synchronized数据,所以仍可被同时会见(代码(2)中的sleep()函数由于在暂停时不会释放“符号锁”,因为线程中的轮回很难被间断去执行另一个线程,所以代码(2)只是为了显示功效)。

假如把例7中的代码(3)注释掉,并去年月码(4)的注释,运行功效将为:

t1 : 0

t1 : 1

t1 : 2

t1 : 3

t1 : 4

t1 : 5

t1 : 6

t1 : 7

t1 : 8

t1 : 9

t2 : 0

t2 : 1

t2 : 2

t2 : 3

t2 : 4

t2 : 5

t2 : 6

t2 : 7

t2 : 8

t2 : 9

修改后的t1、t2是同一个工具(r1)的线程,所以只有当一个线程(t1或t2中的一个)执行run()函数,另一个线程才气执行。

2.3 工具的“锁符号”和class的“锁符号”是彼此独立的。

#p#分页标题#e#

例8:

class TestSynchronized extends Thread
{
  public TestSynchronized(String name)
  {
   super(name);
  }
  public synchronized static void prt()
  {
   for(int i=10; i<20; i++)
   {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
  public synchronized void run()
  {
   for(int i=0; i<10; i++)
   {
    System.out.println(Thread.currentThread().getName() + " : " + i);
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
}
public class TestThread
{
  public static void main(String[] args)
  {
   TestSynchronized t1 = new TestSynchronized("t1");
   TestSynchronized t2 = new TestSynchronized("t2");
   t1.start();
   t1.prt(); //(1)
   t2.prt(); //(2)
  }
}

#p#副标题#e#

运行功效为:

main : 10

t1 : 0

main : 11

t1 : 1

main : 12

t1 : 2

main : 13

t1 : 3

main : 14

t1 : 4

main : 15

t1 : 5

main : 16

t1 : 6

main : 17

t1 : 7

main : 18

t1 : 8

main : 19

t1 : 9

main : 10

main : 11

main : 12

main : 13

main : 14

main : 15

main : 16

main : 17

main : 18

main : 19

在代码(1)中,固然是通过工具t1来挪用prt()函数的,但由于prt()是静态的,所以挪用它时不消颠末任何工具,它所属的线程为main线程。

由于挪用run()函数取走的是工具锁,而挪用prt()函数取走的是class锁,所以同一个线程t1(由上面可知实际上是差异线程)挪用run()函数且还没完成run()函数时,它就能挪用prt()函数。但prt()函数只能被一个线程挪用,如代码(1)和代码(2),纵然是两个差异的工具也不能同时挪用prt()。

#p#副标题#e#

3. 同步的优化

1) synchronized block

语法为:synchronized(reference){ do this }

reference用来指定“以某个工具的锁符号”对“大括号内的代码”实施同步节制。

例9:

class TestSynchronized implements Runnable
{
  static int j = 0;
  public synchronized void run()
  {
   for(int i=0; i<5; i++)
   {
    //(1)
    System.out.println(Thread.currentThread().getName() + " : " + j++);
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
}
public class TestThread
{
  public static void main(String[] args)
  {
   TestSynchronized r1 = new TestSynchronized();
   TestSynchronized r2 = new TestSynchronized();
   Thread t1 = new Thread(r1, "t1");
   Thread t2 = new Thread(r1, "t2");
   t1.start();
   t2.start();
  }
}

运行功效为:

t1 : 0

t1 : 1

t1 : 2

t1 : 3

t1 : 4

t2 : 5

t2 : 6

t2 : 7

t2 : 8

t2 : 9

上面的代码的run()函数实现了同步,使每次打印出来的j老是不沟通的。但实际上在整个run()函数中,我们只体贴j的同步,而其余代码同步与否我们是不体贴的,所以可以对它举办以下修改:

class TestSynchronized implements Runnable
{
  static int j = 0;
  public void run()
  {
   for(int i=0; i<5; i++)
   {
    //(1)
    synchronized(this)
    {
     System.out.println(Thread.currentThread().getName() + " : " + j++);
    }
    try
    {
     Thread.sleep(100);
    }
    catch(InterruptedException e)
    {
     System.out.println("Interrupted");
    }
   }
  }
}
public class TestThread
{
  public static void main(String[] args)
  {
   TestSynchronized r1 = new TestSynchronized();
   TestSynchronized r2 = new TestSynchronized();
   Thread t1 = new Thread(r1, "t1");
   Thread t2 = new Thread(r1, "t2");
   t1.start();
   t2.start();
  }
}

运行功效为:

t1 : 0

t2 : 1

t1 : 2

t2 : 3

t1 : 4

t2 : 5

t1 : 6

t2 : 7

t1 : 8

t2 : 9

#p#分页标题#e#

由于举办同步的范畴缩小了,所以措施的效率将提高。同时,代码(1)指出,当对大括号内的println()语句举办同步节制时,会取走当前工具的“锁符号”,即对当前工具“上锁”,不让当前工具下的其它线程执行当前工具的其它synchronized数据。

 

    关键字:

[contact-form-7 id="17097" title="form2"]天才代写-代写联系方式