1. There are 2 ways to use threads in Java:
(1) Inherit the thread class
(2) Implement Runnable interface
Here is an example to illustrate:
Way One:
Class Test extends Thread{public void run () {sysout.println ("Thread Test ...")}}public class Threadtest{public static void Main (string[] args) { Thread t = new Test (); T.start ();}}
Way two:
Class Test implements Runnable{public void Run () { System.out.println ("Runnable Test ...");}} public class Threadtest{public static void Main (string[] args) {Test t = new Test (); Thread th = new Thread (t); Th.start ();}}
Wall crack determination is in two ways, because Java classes are single inheritance, multi-implementation, when a class inherits other classes, but also want to implement multi-threading, you can not use inheritance, can only be implemented interface.
2. Thread has some security issues
An example of a ticket purchase:
Class Ticket implements runnable{private int Ticket = @Overridepublic void Run () {while (true) {if (ticket>0) {try {Th Read.sleep (10);} catch (Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "---" +ticket--);}}} public class Ticketdemo {public static void main (string[] args) {Ticket Ticket = new Ticket (); Thread t = new thread (ticket); Thread t2 = new Thread (ticket); thread t3 = new thread (ticket); thread T4 = new thread (ticket); T.start (); T2.start (); T3.start (); T4.start ();}}
It will appear after running:
0 and 1 also appeared, which is not supposed to happen.
Explanation Reason: Suppose now only one ticket, by thread 1 Rob, because Thread.Sleep (10); Causes other threads to also enter, when Thread-1 wakes up the number of votes minus one, the current number of votes is 0, but when other threads wake up and then go minus one, the ticket number is already 0, which is why the votes are 0,-1.
How to solve? Add synchronized code blocks where you manipulate the data.
public void Run () {while (true) {synchronized (the This) {/////Synchronized code block if (ticket>0) {try {thread.sleep];} catch ( Interruptedexception e) {e.printstacktrace ();} System.out.println (Thread.CurrentThread (). GetName () + "---" +ticket--);}}}
If you do not use this on the Run method plus the static synchronization code block, the Ticket.class object should be used because of the class loading, and the bytecode object for the class already exists when the class is loaded, but the instance object does not exist and needs to be created with the New keyword.
Here is a picture of a thread:
The last example is a chat code that is combined with thread and network programming: (If two client communication remember to modify IP)
Package Com.core.net;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStreamReader; Import Java.net.datagrampacket;import Java.net.datagramsocket;import Java.net.inetaddress;class MSend implements Runnable{private datagramsocket socket;public msend (datagramsocket socket) {this.socket = socket;} @Overridepublic void Run () {BufferedReader reader = null;try {reader = new BufferedReader (New InputStreamReader (system.in )); String line = null;while (line = Reader.readline ())!=null) {if (' 886 '. Equals line) {break;} byte[] buf = Line.getbytes (); Datagrampacket DP = new Datagrampacket (buf, Buf.length, Inetaddress.getbyname ("192.168.23.255"), 8887); Socket.send (DP);}} catch (Exception e) {throw new RuntimeException ("Send side Failed");} Finally{try {reader.close ();} catch (IOException e) {e.printstacktrace ();} Socket.close ();}}} Class Mrecevice implements Runnable{private datagramsocket socket;public Mrecevice (datagramsocket socket) {This.socket = socket;} @Overridepublic void Run () {try {while (true) {byte[] buf = new byte[1024];D atagrampacket dp = new Datagrampacket (Buf,buf.len GTH); socket.receive (DP); String IP = dp.getaddress (). gethostaddress (); String data = new String (Dp.getdata (), 0,dp.getlength ()); System.out.println (ip+ ":" +data);}} catch (Exception e) {throw new RuntimeException ("Receiver failed");}}} public class Chatdemo {public static void main (string[] args) throws Exception {Datagramsocket send = new Datagramsocke T (); Datagramsocket rece = new Datagramsocket (8887); New Thread (new Msend (send)). Start (); New Thread (New Mrecevice (Rece)). Start (); }}
Java Threading Summary