Java
A thread refers to an execution task in a process. A process can run multiple threads, and multiple threads can share data.
A process has at least one thread. To improve efficiency, you can enable multiple tasks in a process.
The thread can run at the same time, but through the results of the program running, it is found that although running at the same time, the results are different each time.
Threads have many characteristics of traditional processes and can become lightweight processes.
Turning a traditional process into a heavy process is equivalent to only one thread executing the task. In the operating system where threads are introduced, a process usually has several threads and at least one thread.
Differences between processes and threads:
Thread creation method:
1. Inheritance
String name=Thread.currentThread().getName(); ( i = 1; i <=50; i++ System.out.println(name+"--->"+ (i==20 MyThread().start(); MyThread ( i = 1; i <=50; i++ System.out.println(.getName()+ }
2. Implementation
MyThread1 my = ( i = 0; i < 50; i++ System.out.println(Thread.currentThread().getName()+"---->"+ (i==25 Thread(my,"leo" MyThread1 ( i = 0; i < 50; i++ System.out.println(Thread.currentThread().getName()+"--->"+ }
Thread ticket selling instance:
TicketThread ("Window 1" TicketThread ("window 2" TicketThread ("window 3" TicketThread ticketNumber = 10 (I = 0; I <ticketNumber; I ++ System. out. println (. getName () + "sell" + ticketNumber -- + "ticket "}
Result:
Sell ticket No. 10 in window 1
Sell ticket No. 9 in window 1
Sell ticket No. 8 in window 1
Sell ticket No. 7 in window 1
Sell ticket No. 6 in window 1
Sell ticket No. 10 in window 2
Sell ticket No. 9 in window 2
Sell ticket No. 8 in window 2
Sell 7 tickets in window 2
Sell ticket No. 6 in window 2
Sell ticket No. 10 in window 3
Sell ticket No. 9 in window 3
Sell ticket No. 8 in window 3
Sell 7 tickets in window 3
Sell ticket No. 6 in window 3
As you can see, if you go to the train station to buy a ticket, then the conductor will buy a ticket in this way... it will cause a conflict! Since the No. 1 window has sold the No. 10 seat, why do I need to continue selling it? So it's not good ......
Runnable:
MyTicket target = Thread (target, "Window 1" Thread (target, "window 2" Thread (target, "window 3" MyTicket ticketNumber = 10 (I = 0; I <= 200; I ++ (. ticketNumber> 0 System. out. println (Thread. currentThread (). getName () + "sell" + ticketNumber -- + "ticket "}
Result:
Sell ticket No. 10 in window 1
Sell ticket No. 8 in window 3
Sell ticket No. 9 in window 2
Sell ticket No. 6 in window 3
Sell ticket No. 7 in window 1
Sell ticket No. 4 in window 3
Sell ticket No. 5 in window 2
Window 3 sells ticket No. 2
Sell ticket No. 3 in window 1
Sell ticket No. 1 in window 2
The results of these two methods are obviously easy to see ......................